hellosheikh hellosheikh -4 years ago 117
PHP Question

Fetch data from multiple tables Cakephp

hello I have four tables and I am trying to fetch data from all of them.
Tables are


  1. User

  2. UserInfo

  3. Category

  4. UserCategory



Since user can select multiple categories so I have setup a separate table called
UserCategory
. This table has
user_id
and
cat_id
as foreign key of
user
and
Category
Table fields

In
Category
Table, the field is
cat_name


I want to get All the data from all the four tables associated with the particular userID. So at the moment I have achieved this. I'll show you how.



class UserInfo extends AppModel
{
public $useTable = 'user_info';
public $primaryKey = 'user_id';


public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'type' => 'RIGHT',
'fields' => array('User.user_id','User.email','User.active')
)


);
public $hasMany = array(
'UserCategory' => array(
'className' => 'UserCategory',
'foreignKey' => 'user_id',
'conditions' => array('user_id = UserCategory.user_id')
//'order' => 'UserCategory. DESC'
),


);
public function getUserDetails($user_id){
return $this->find('all', array(
'conditions' => array(
'UserInfo.user_id' => $user_id
),


));

}


By doing this

$userDetails = $this->UserInfo->getUserDetails($user_id);


I get a result like this

Array
(
[0] => Array
(
[UserInfo] => Array
(
[user_id] => 9
[first_name] => lorem
[last_name] => ipsum
[phone_no] => 123
[profile_img] => app/webroot/uploads/9/589c538daa276test.png.png
[registration_date] => 2017-02-09 08:33:33
[device_token] => ddd222
)

[User] => Array
(
[user_id] => 9
[email] => new email
[active] => 1
)

[UserCategory] => Array
(
[0] => Array
(
[user_category_id] => 1
[user_id] => 9
[cat_id] => 1
)

[1] => Array
(
[user_category_id] => 3
[user_id] => 9
[cat_id] => 1
)

[2] => Array
(
[user_category_id] => 4
[user_id] => 9
[cat_id] => 2
)

)

)

)


I want to know how Can I get Category names from category table in the above array.

Answer Source

You can use containable in this case.

    public function getUserDetails($user_id){
        $this->Behaviors->attach('Containable');
        return $this->find('all', array(
            'conditions' => array(
                'UserInfo.user_id' => $user_id
            ),
            'contain' => array(
                'User', 'UserCategory.Category'
            )
        ));
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download