0
votes

So I have 3 tables: Users, Customers and Bookings.

The relationship and foreign keys between each:

Users hasOne Customers. Customers belongsTo Users. Users.id = Customers.user_id

Customers hasMany Bookings. Bookings belongsTo Customers. Customers.id = Bookings.customer_id

In an add form, when making a booking, I want to save the logged in user's customer id as the booking's customer_id.

Fields:

In Users table:

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

In Customers table:

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

In Bookings table:

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

2
isnt user == customer? What have you tried? Did you follow conventions?Alex Stallen
User and customer are separated for security purposes - User has username and password, Customer has name & phone number. I've tried: $customer = $booking->Customers->findByuser_id('Auth.User')->first();mistaq
what is secure about it?Alex Stallen
Sorry, jumped to conclusions. But in my database, my user table is connected to another table, i.e. all Customers are Users, but not all Users are Customers.mistaq

2 Answers

1
votes

You can try below code

$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
    }
}

Finding Customer ID (Loading Model)

$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'];

Finding Customer ID (Without Loading Model)

$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
votes

Check out the Footprint plugin, which handles exactly this problem pretty transparently.