Help confused on HasOne and HasMany logic in cakephp 3.6


#1

Sorry I get confused on the code I need to put in place in the table files to indicate that I have a foreign key back to a table. So here it goes:

I have a clients table with a primary key with a column name of id. I I also have a Deliveries table that has a client_id column that is a foreign key back to the clients table referencing the id column. What do I put in both the Clients Table and the Deliveries Table during initialization.

For example:

$this->hasone('Clients')->setForeignKey('client_id')->setJoinType('INNER');

is in my Deliveries Table class but this produces an inner join where it thinks the Clients table has the column client_id but in fact the Deliveries table has the client_id foreign key. So does the above code need to go in the ClientsTable class?

Help !


#2

This is what you need.

Clients hasMany Deliveries - (Docs here https://book.cakephp.org/3.0/en/orm/associations.html#belongsto-associations)

class ClientsTable extends Table {
   public function initialize(array $config) {
      $this->hasMany('Deliveries');
   }
}

Deliveries belong to a Client (table deliveries will have client_id in it, details here - https://book.cakephp.org/3.0/en/orm/associations.html#belongsto-associations

class DeliveriesTable extends Table {
   public function initialize(array $config) {
      $this->belongs('Clients');
   }
}