CakePhp where()条件不适用于HasMany关系

时间:2019-12-15 18:30:38

标签: cakephp cakephp-3.x cakephp-3.8

我要吃饭

'ormconfig.json'
{
   "type": "mysql",
   "host": "localhost",
   "port": 3306,
   "username": "test",
   "password": "test",
   "database": "test"
}

注意:产品可能包含多个供应商库存。

在模型/表/供应商库存中

1. Products
2. VendorsInventories 

在以下位置:Model / Table / ProductsTable.php

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

在查询中:

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

结果是:

Response ofcode

我的主要问题是:如何选择包含关系数据的行。 N.B:belongsTo()工作正常,我对hasToMany()有问题

1 个答案:

答案 0 :(得分:1)

检查CakePHP Conventions

  

hasMany,beforeTo / hasOne关系中的外键被识别   默认为相关表的(单数)名称,后跟   _id。因此,如果Users hasMany Articles,则articles表将通过users外键引用user_id表。对于像这样的桌子   article_categories,其名称包含多个单词,即外键   应该是article_category_id

因此,更改

'foreignKey' => 'products_id',

'foreignKey' => 'product_id',