Kapil Sharma Kapil Sharma - 4 months ago 18
MySQL Question

create proper association in cakephp 3

I want to create proper relation b/w two table. So that when I get data from

lease
table I will be able to get
price
table data too. Price table can have multiple id of
lease
table.

The structure of tables are

Lease Table

enter image description here

Price Table

enter image description here

Where
id
of
lease
table related to
lease_id
of price table.

I have tried with following code but not able to get data.

class LeasesTable extends Table {

/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config) {
parent::initialize($config);

$this->table('leases');

$this->primaryKey('id');

$this->addBehavior('Timestamp');

$this->belongsTo('Offices', [
'foreignKey' => 'office_type',
'joinType' => 'INNER'
]);
$this->belongsTo('Countries', [
'foreignKey' => 'country_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Areas', [
'foreignKey' => 'area_id',
'joinType' => 'INNER'
]);
$this->belongsToMany('id', [
'foreignKey' => 'lease_id',
'joinType' => 'INNER',
'joinTable' => 'Prices',
]);
}

Answer Source

Association you described is Lease has many Prices - so you should use following code in LeasesTable.php:

$this->hasMany("Prices", [
    "foreignKey" => "lease_id"
]);

More info: HasMany Associations