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. 

<?php
use Cake\ORM\TableRegistry;

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

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

user
Kristi

137

Accepted by Kristi

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

<?php
use Cake\ORM\TableRegistry;

//...in controller
TableRegistry::get('Users')->find('all', [
      'fields' => ['Users.id', 'Users.name'],
      'conditions' => ['Users.id' => 1]
])
->contain([
	'Posts' => [
		'fields' => ['title']
	]
])
->first();
nithin
nithin

17

Created: 31 Aug '16

Last Reply: 11 Oct '16

Replies: 1

Views: 604

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