我正在尝试创建以下数据库结构:
http://www.databaseanswers.org/data_models/generic_pos/index.htm
具体来说,我正在研究:
之间的关系sales_transaction
products
products_in_transaction
我想要关系设置,以便我可以调用sales_transaction
数据库,然后只包含products
,并在1个查询中获取所有内容。
但是,它只是工作,所以请帮助我: - )
这是我的代码:
SalesTransactionTable
public function initialize(array $config)
{
parent::initialize($config); // TODO: Change the autogenerated stub
$this->hasMany('Products', [
'through' => 'ProductsInTransaction'
]);
}
ProductsTable
public function initialize(array $config)
{
parent::initialize($config); // TODO: Change the autogenerated stub
$this->belongsToMany('SalesTransaction', [
'through' => 'ProductsInTransaction'
]);
}
ProductsInTransactionTable
public function initialize(array $config)
{
parent::initialize($config); // TODO: Change the autogenerated stub
$this->belongsTo('SalesTransaction', [
'foreignKey' => 'transaction_id',
'joinType' => 'inner'
]);
$this->belongsTo('Products', [
'foreignKey' => 'product_id',
'joinType' => 'inner'
]);
}
从上述陈述中可以明显看出这种关系。本质上,SalesTransaction
包含我的所有交易,而products_in_transaction
是我的连接表,可以将它与products
连接起来,但只需查看链接即可获得完整的方案。
当我尝试运行此代码来获取它时:
$sales_transactions = $sales_transactions_table->find('all', [
'conditions' => [
'device_id IN' => $deviceIdsInDepartment
],
'contain' => [
'Products'
]
]);
答案 0 :(得分:1)
您在hasMany
模型中使用SalesTransaction
关联。
它应该是belongsToMany
:
<强> SalesTransactionTable 强>
$this->belongsToMany('Products', [
'through' => 'ProductsInTransaction'
]);