简体   繁体   中英

Cakephp Complex Query buiding

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM