Cakephp Complex Query buiding

64 Views Asked by At

I have three tables users, attributes and user_attributes.

users[id, name, username, password, dob, gender, isactive, registered_on],
attributes[id, name, isactive],
user_attributes[id, user_id, attribute_id]

This is my table structure with fields. Now I want to write a query which will fetch all the users from user table along with the value of user_attributes table if there any row exist in user_attributes table.

How to write the query in cakephp? I have two Models User and Attribute.

Thanks in advance.

1

There are 1 best solutions below

1
sanjay verma On

Follow these steps:

1-Create a Model UserAttribute for table user_attributes.

class UserAttribute extends AppModel{

}

2- In your User Model create hasMany association with UserAttribute

class User extends AppModel{

   public $hasMany = array(
            'UserAttribute' => array(
            'className' => 'UserAttribute',
            'foreignKey' => 'user_id',

            ),

     );

 }

3- Do find query in your controller:

$users= $this->User->find('all');
echo "<pre>";
print_r($users);