I have the next question.
There is part of code:
$result = $this->find('all', array(
'contain' => array(
'User' => array(
'fields' => 'id',
'conditions' => array(
'id' => $user_id
)
)
),
'fields' => 'url'
));
This find() called in method of Project model class and I want to retrieve just projects where User.id equal some user id passed to my method.
User HABTM Project and Project HABTM User.
But after executing I have the next:
app/views/projects/index.ctp (line 1)
Array
(
[0] => Array
(
[Project] => Array
(
[url] => http://purpled.biz
[id] => 1
)
[User] => Array
(
[0] => Array
(
[id] => 4
[ProjectsUser] => Array
(
[user_id] => 4
[project_id] => 1
[projects_users_role_id] => 0
)
)
)
)
[1] => Array
(
[Project] => Array
(
[url] => http://google.com
[id] => 2
)
[User] => Array
(
[0] => Array
(
[id] => 4
[ProjectsUser] => Array
(
[user_id] => 4
[project_id] => 2
[projects_users_role_id] => 0
)
)
)
)
[2] => Array
(
[Project] => Array
(
[url] => http://test.com
[id] => 3
)
[User] => Array
(
)
)
)
As you see there is the last array with empty [User] array, so how can I exclude this empty array (whole [2] array I mean) without using foreach/if blocks? I know that using bindModel will do all as well but this is not for my question 😉 So, how?
Placing your conditions within the ‘contain’ key will filter the results within that particular model.
Retrieving the right data
I’ve answered a question before very similar to this here. You would just need to replace the models mentioned there with your own models. If you have trouble understanding the answer there, let us know.
Tips for your current model structure
I notice that your ProjectsUser model has an extra field “projects_users_role_id”. When your Join Model is complex (more than just id, model1_id, model2_id), then you need to represent it by a model in itself. It’s generally referred to as a hasMany Through relationship.
You could also rename “ProjectsUser” to something nicer like “ProjectMembership”.