CakePhp where() condition is not working on HasMany relation

455 Views Asked by At

I have to table

1. Products
2. VendorsInventories 

NB: Product may contain more than one VendorsInventories.

In Model/Table/VendorsInventories

    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('vendors_inventories');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');

        $this->belongsTo('Products', [
            'foreignKey' => 'products_id',
            'joinType' => 'INNER'
        ]);
    }

And in: Model/Table/ProductsTable.php

    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('products');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');
        $this->addBehavior('Timestamp');
        $this->hasMany('VendorsInventories',[
            'foreignKey' => 'products_id',
            'joinType' => 'INNER'
        ]);
    }

in query:

$products=$this->Products->find('all')->contain(['VendorsInventories']);

and the result is:

Response ofcode

My main question is: How to seletct rows which contain Relation data. N.B: belongsTo() is working fine, i have problem with hasToMany()

1

There are 1 best solutions below

0
On

Check the CakePHP Conventions

Foreign keys in hasMany, belongsTo/hasOne relationships are recognized by default as the (singular) name of the related table followed by _id. So if Users hasMany Articles, the articles table will refer to the users table via a user_id foreign key. For a table like article_categories whose name contains multiple words, the foreign key would be article_category_id.

So, change

'foreignKey' => 'products_id',

to

'foreignKey' => 'product_id',