【问题标题】:cakephp 3 deeper associationscakephp 3 个更深层次的关联
【发布时间】:2015-08-29 21:51:45
【问题描述】:

我正在尝试找到处理下一个表格设置的正确方法。

Products 是我的主表,包含一个 ID。 UsersCarts 有一个字段 product_id 和 belongsTo 它还加载产品。

到目前为止没有问题。我还有一张 ProductsNettoDeals 表,用于存储可能的净价格。当在 productcontroller 中加载产品时,该表具有自己的 id 和 hasOne 关系的 product_id。

当我加载 UsersChart 时,它会加载它属于产品,但我也希望与表 ProductsNettoDeals 关联,但该表通过 id (products.id = products_netto_deals.product_id) 与产品连接。我找不到查询构建器的正确语法或关联。到目前为止我所拥有的:

// src/Model/Table/UsersCartsTable.php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\ORM\Query;
use Cake\Validation\Validator;

class UsersCartsTable extends Table
{

public function initialize(array $config)
{
    $this->addBehavior('Timestamp');
    $this->belongsTo('Products');
    $this->belongsTo('ProductsNettoDeals');
}

public function validationDefault(Validator $validator)
{
    return $validator
        ->notEmpty('user_id', 'A user id is required')
        ->notEmpty('product_id', 'A product id is required');
}

public function findCart(Query $query, array $options)
{
    $query 
    ->where([
    'user_id' => $options['user_id'],
    //'active' => '1'
    ])
    ->contain(['Products','ProductsNettoDeals'])
    //->select(['product_id','created','products.name','products.price','products.delivery_time']);
    ;

    return $query;
}
}

在此设置中,我总是遇到 id 匹配错误的问题。有了产品就好了。 users_carts.product_id 链接到 products.id,但 products_netto_deals.product_id 应该链接到 product.id 而不是 users_carts.id。我尝试了外键和绑定,但两者都是解决方案的一部分。

除了这个问题之外,在连接关联 ProductsNettoDeals 时,我在激活注释为 active => '1' 时遇到错误。此字段指示记录是否处于活动状态并应加载。 products_netto_deals 表中存在相同的字段,用于指示净价格是否有效。

错误:SQLSTATE[23000]:违反完整性约束:1052 where 子句中的“活动”列不明确

任何人都可以为我指出正确的关联方式和错误警告的正确方向。谢谢转发。

【问题讨论】:

    标签: associations cakephp-3.0


    【解决方案1】:

    CakePHP 使用连接来获取关联,以加快信息检索过程。这意味着当在不同的表中重复列名时,您需要在查询子句中为列名添加前缀"

    代替:

    $query->where(['active' => true]);
    

    做:

    $query->where(['UsersCarts.active' => true])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多