简体   繁体   中英

Cakephp Find behavior Containable not working

I have three Models

  1. User
  2. Note ( Same as Post )
  3. Friendship

I am trying to retrieve posts that are shared by the users to whom i am Subscribed to.

What exactly i did in my UsersController is that i first retrieved the list of all of my friends

 $lof=$this->User->Friendship->find('all', array('conditions'=>array('Friendship.user_from'=>$this->Auth->user('id')), 'contain'=>array('Friendship.user_to')));

Now i am trying to show all the posts shared by my friends

$allnotes= $this->User->Note->find('all', array('conditions'=>array('Note.user_id'=>array($lof)), 'order' => array('Note.created DESC')));

Which gives me an error

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'where clause'

SQL Query: SELECT `Note`.`id`, `Note`.`user_id`, `Note`.`notes`, `Note`.`created`,     `User`.`id`, `User`.`name`, `User`.`email`, `User`.`username`, `User`.`password`, `User`.`gender`, `User`.`dob`, `User`.`image`, `User`.`tmp_name`, `User`.`search` FROM `fyp`.`notes` AS `Note` LEFT JOIN `fyp`.`users` AS `User` ON (`Note`.`user_id` = `User`.`id`) WHERE `Note`.`user_id` = (Array) ORDER BY `Note`.`created` DESC

I know i am trying to add an array but when i tried the same find query like this, it worked.

$allnotes= $this->User->Note->find('all', array('conditions'=>array('Note.user_id'=>array(114,115)), 'order' => array('Note.created DESC')));

What exactly is the solution to get only the values of user_to from Friendship table and assign it equals to Note.user_id in my query.

The problem is that your $lof variable doesn't contain an array of id's. It will contain the full array of data from the Friendship model. If you view the value of the $lof variable you should see what I mean. You can do this using the debug() function.

To do what you want to do you'll have to use the 'list' find method and use the Friendship.user_to field. Like this:

$lof = $this->User->Friendship->find('list', array(
    'fields' => array('Friendship.id', 'Friendship.user_to'),
    'conditions' => array(
        'Friendship.user_from' => $this->Auth->user('id')
));

And then to find all the notes you can now use

$allnotes = $this->User->Note->find('all', array(
    'conditions' => array(
         'Note.user_id' => $lof
     ),
     'order' => array('Note.created DESC')
));

You can read more about the different find methods (I've linked to the list one) in CakePHP's cookbook

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