Category: Models & ORM

Q: Work with contain hasMany association and to retrieve particular fields only?

I'd like to know how to retrieve particular fields in the associated table when using containable queries? To be more specified, I have the following tables: Posts, Users that a user may have one or many posts. The foreign key was set up appropriately in users table. 

use Cake\ORM\TableRegistry;

// controller
TableRegistry::get('Users')->find('all', array(
      'contain' => array('Posts'),
      'fields' => array('', '', 'Posts.title'),
      'conditions' => array('' => 1)

Cakephp console shows that "unknown column Posts.title in field list.

And for more, is there a way to get like 'Posts.*' in field list?

SOLVED contain association hasmany
1 Answers

Version: 3.2



Accepted by Kristi

There are many ways to do this. This is one method. Hope this helps you.

use Cake\ORM\TableRegistry;

// controller
TableRegistry::get('Users')->find('all', [
      'fields' => ['', ''],
      'conditions' => ['' => 1]
	'Posts' => [
		'fields' => ['title']


Created: 31 Aug '16

Last Reply: 11 Oct '16

Replies: 1

Views: 4970

Votes: 0

Welcome to Aero Coding!

Aero Coding is a CakePHP-focused Q&A community for professional and enthusiast cake bakers. It's built and run by you as part of the community.

Join Now Tour

Download Cakephp

Start baking your own CakePHP application!

Cakephp All Versions