silentcoder
silentcoder

Reputation: 1048

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',
        ]);
    }

Upvotes: 0

Views: 34

Answers (1)

Szymon
Szymon

Reputation: 1415

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

Upvotes: 2

Related Questions