Donal.Lynch.Msc
Donal.Lynch.Msc

Reputation: 3615

CakePHP Query building question

I am trying to display a list of friends names ie: first_name and last_name.

I have a friendships table, which looks like this:

id , friend_a , friend_b , created , modified
1 , 1 , 3 , created , modified
1 , 1 , 7 , created , modified
1 , 4 , 1 , created , modified
1 , 2 , 6 , created , modified

where friend_a and friend_b are friends.

Then I have a friendships_controller, with this:

function get_my_friends(){
    $this->set('user', $this->passedArgs['user']   ); 

    $conditions = array(
        'OR' => array(
        array( "Friendship.friend_a" => $this->passedArgs['user']),
        array( "Friendship.friend_b" => $this->passedArgs['user'])
        )
    );

    $this->set('friends', $this->Friendship->find('all',array('conditions'=>$conditions))  );   
}

And in the view, I have this:

<?php foreach( $friends as $friend ): ?> ... 

And for each $friend, I want to echo the name of that friend, which needs to be retrieved from the users table.

QUESTION:

How do I also integrate into the above controller query:

SELECT first_name, last_name FROM users AS friend_name WHERE users.id = x

Where x represents the clause ((if $user == Friendship.friend_a, then SELECT friend_b)else((SELECT friend_a))")

Any help appreciated...

Upvotes: 0

Views: 101

Answers (1)

Anh Pham
Anh Pham

Reputation: 5481

set Friendship belongsTo User (or whatever model you use; remember to set 2 of them, 1 for friend_a, 1 for friend_b); set app_model to actAs Containable; and in the code:

$this->set('friends', $this->Friendship->find('all',array(
    'conditions'=>$conditions)),
    'contain'=>array(
       'name_of_the_relationship_you_set_for_friend_a'=>array('fields'=>array('first_name', 'last_name')),
       'name_of_the_relationship_you_set_for_friend_b'=>array('fields'=>array('first_name', 'last_name'))
    )
  );

If any of the above is new to you, look it up in the cookbook.

Upvotes: 1

Related Questions