Tuesday, January 22, 2013

A find condition about hasMany(has many) relationship in cakephp

Suppose you have two model User and UserRole.
And User has many UserRole.
Now you want to find User By specific UserRole.

User:
Fields: id, name, others........
var $hasMany = array(
    "UserRole"
);

UserRole:
Fields: id, user_id, role_id, others...var 
$belongsTo = array("User");

First you need to find all UserRole by your own conditions:

$userRoles = $this->UserRole->find("all", array(
    "conditions" => array(
        "UserRole.condition" => $value
    )
));

Now find User by UserRole as follows:

$users = $this->User->find("all", array(
    "conditions" => array(
        "User.id" => Set::extract("/UserRole/user_id", $userRoles)
    )
));


BINGO...

No comments:

Post a Comment