所以我有3个表:用户,客户和预订。
每个之间的关系和外键:
用户拥有一个客户。客户属于用户。 Users.id = Customers.user_id
客户有很多预订。预订属于客户。 Customers.id = Bookings.customer_id
在添加表单中,我在预订时希望将登录用户的客户ID保存为预订的customer_id。
字段:
在用户表中:
-id
-username
-password
-role_id(连接到角色表) -created
- 修改
在客户表中:
-id
-user_id(连接到Users表的外键)
-name
-created
- 修改
在预订表中:
-id
-customer_id(连接到Customers表的外键)
-payment_id(连接到付款表)
-created
- 修改
答案 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'];
答案 1 :(得分:0)
查看Footprint plugin,它可以非常透明地处理这个问题。