CakePHP 3 - 通过其他表连接?

时间:2017-12-28 11:47:06

标签: php mysql cakephp associations cakephp-3.x

我正在尝试创建以下数据库结构:

enter image description here

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

我收到此错误: error

1 个答案:

答案 0 :(得分:1)

您在hasMany模型中使用SalesTransaction关联。

它应该是belongsToMany

<强> SalesTransactionTable

$this->belongsToMany('Products', [
    'through' => 'ProductsInTransaction'
]);