CakePHP 3 - 通过其他表连接?

问题描述 投票:0回答:1

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

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

php mysql cakephp associations cakephp-3.x
1个回答
1
投票

你在hasMany模型中使用了SalesTransaction关联。

它应该是一个belongsToMany

SalesTransactionTable

$this->belongsToMany('Products', [
    'through' => 'ProductsInTransaction'
]);
© www.soinside.com 2019 - 2024. All rights reserved.