PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 10, 2022

[FIXED] CakePHP3 'contain' doesn't retrieve 'belongsTo'

 March 10, 2022     cakephp, cakephp-3.0     No comments   

Issue

A user has multiple products. Each product has a brand.

In the Products Table, I have a "brand_id" column.

For the moment there is no join when I do debug($user).

I would like a join between Brands and Products Tables (product.brand_id = brand.id). How can I solve this ?

(sorry for my english)

//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');
}

Solution

Simple:

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

read more: https://book.cakephp.org/4/en/orm/query-builder.html#loading-associations



Answered By - Salines
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing