我必须上桌
1. Products
2. 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'
]);
}
并且在: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'
]);
}
查询中:
$products=$this->Products->find('all')->contain(['VendorsInventories']);
结果是:
我的主要问题是:如何选择包含关系数据的行。N.B:belongsTo()工作正常,我对hasToMany()有问题 我必须表1.产品2.供应商库存注意:产品可能包含多个供应商库存。在Model / Table / VendorsInventories中,公共函数initialize(array $ config){...
hasMany,belongsTo / hasOne关系中的外键被识别默认为相关表的(单数)名称,后跟
_id
。因此,如果用户hasManyArticles
,则articles
表将通过users
外键引用user_id
表。对于像这样的桌子article_categories
其名称包含多个单词,即外键将会是article_category_id
。
因此,更改
'foreignKey' => 'products_id',
to
'foreignKey' => 'product_id',