Tuesday, May 1, 2012

Re: Looping through associated data (hasMany)

It's straightforward PHP:

if (!empty($user['Post']))) {
foreach ($user['Post'] as $post) {
// do something
}
}

(...where $user is the array that contains this data).

Jeremy Burns
Class Outfit

http://www.classoutfit.com

On 1 May 2012, at 12:11:53, JonStark wrote:

So I'm currently configuring my model relationship, and the array returns all needed info.

But I have question :

On my app, User hasMay Post,

and so arrays look like this on User/view.ctp :

array(  	'User' => array(  		'password' => '*****',  		'id' => '1',  		'email' => 'test@test.com',  	),  	'Post' => array(  		(int) 0 => array(  			'id' => '1',  			'title' => 'title',  			'body' => 'Lorem ipsum dolor sit amet',    		),  		(int) 1 => array(  			'id' => '2',  			'title' => 'Test',  			'body' => 'Lorem ipsum dolor sit amet',    		),  		(int) 2 => array(  			'id' => '9',  			'title' => 'A photo',  			'body' => 'http://lorempixel.com/500/400/',    		)  	),    )

So, if I want to print Post info, I must do this :

echo $user['Post']['0']['body'];
echo $user['Post']['0']['title'] ;

echo $user['Post']['1']['body'];
echo $user['Post']['1']['title'] ;

and so on.

How can I loop through this associated data so If the user has 5 posts or 1 or 0 I can display it with something like foreach ?

Thanks a lot.

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
 
 
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: