【问题标题】:CakePHP3 'contain' doesn't retrieve 'belongsTo'CakePHP 3“包含”不检索“属于”
【发布时间】:2021-12-27 22:47:02
【问题描述】:

一个用户有多个产品。每个产品都有一个品牌。

在产品表中,我有一个“brand_id”列。

目前我做debug($user)时没有加入。

我想加入品牌和产品表 (product.brand_id = brand.id)。我该如何解决这个问题?

(对不起我的英语)

//Controller Users
    $users = TableRegistry::getTableLocator()->get('users');
    $user = $users->find('all')
            ->contain(['Products' => ['conditions' => ['id' => 25]]])
            ->first();
    debug($user); 


//Model Users
public function initialize(array $config)
{
    $this->hasMany('products');
}


//model Products
public function initialize(array $config)
{
    $this->belongsTo('brands');
}

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    简单:

    ->contain([
       'Products' => ['conditions' => ['id' => 25]],
       'Products.Brands', // Add product brands
    ])
    

    阅读更多:https://book.cakephp.org/4/en/orm/query-builder.html#loading-associations

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 2016-11-23
      • 2016-01-05
      • 2015-09-29
      • 1970-01-01
      相关资源
      最近更新 更多