2016-10-11 41 views
0

所以我有3个表:用户,客户和预订。保存登录用户的外键作为外键

各关系和外键:

用户有一个客户。客户属于用户。 Users.id = Customers.user_id

Customers hasMany Bookings。预订属于客户。 Customers.id = Bookings.customer_id

在添加表单中,当进行预订时,我想将登录用户的客户ID保存为预订的customer_id。

领域:

在用户表:

-id
-username
-password
-role_id (connected to roles table) -created
-modified

在Customers表:

-id
-user_id (the foreign key connected to Users table)
-name
-created
-modified

在登记表中:

-id
-customer_id (the foreign key connected to Customers table)
-payment_id (connected to payments table)
-created
-modified

+0

isnt user == customer?你有什么尝试?你遵循惯例吗? –

+0

出于安全目的,用户和客户是分开的 - 用户有用户名和密码,客户有姓名和电话号码。我试过了:$ customer = $ booking-> Customers-> findByuser_id('Auth.User') - > first(); – mistaq

+0

什么是安全的? –

回答

1

你可以试试下面Ç颂

$booking = $this->Booking->newEntity(); 
if ($this->request->is('post')) { 
    $data = $this->request->data; #Store post data to a variable 
    $customer_id = #Find and assign customer ID to a variable 
    $data['customer_id'] = $customer_id; #Assign customer ID to saving data 
    $booking = $this->Bookings->patchEntity($booking, $data); 
    if ($this->Bookings->save($booking)) { 
     #SAVING SUCCESS 
    } else { 
     #ERROR SAVING 
    } 
} 

查找客户ID(加载模型)

$this->loadModel('Customers'); 
$logged_in_user_id = $this->Auth->user('id'); 
$customer = $this->Customers->find('all')->where(['user_id'=>$logged_in_user_id])->first(); 
$customer_id = $customer->id; #Or $customer['id']; 

查找客户ID(无负载模型)

$logged_in_user_id = $this->Auth->user('id'); 
$customer = $this->Bookings->Customers->find('all')->where(['user_id'=>$logged_in_user_id])->first(); 
$customer_id = $customer->id; #Or $customer['id']; 
+0

所以用这一行:$ customer_id =,我在哪里查找客户ID?例如,在调试模式下,点击Session然后Auth显示当前登录的用户详细信息,但不显示客户的详细信息。 – mistaq

+0

给我你的客户表'fields' name @ W.Lau –

+0

仍然收到数据库错误。无论如何,我会用领域更新我的OP。 – mistaq