我要吃饭
'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'
]);
}
结果是:
我的主要问题是:如何选择包含关系数据的行。 N.B:belongsTo()工作正常,我对hasToMany()有问题
答案 0 :(得分:1)
hasMany,beforeTo / hasOne关系中的外键被识别 默认为相关表的(单数)名称,后跟
_id
。因此,如果Users hasManyArticles
,则articles
表将通过users
外键引用user_id
表。对于像这样的桌子article_categories
,其名称包含多个单词,即外键 应该是article_category_id
。
因此,更改
'foreignKey' => 'products_id',
到
'foreignKey' => 'product_id',