CakePHP find statement for a sql query involving two models

左心房为你撑大大i 提交于 2019-12-24 08:07:51

问题


I am new to cake and I am practicing with a twitter-like clone. At this point, I have 3 tables:

users (id, name)

  • id is the auto-generated id
  • name of the user

tweets (id, content, user_id)

  • id is the auto-generated id
  • content is the text of the tweet
  • user_id is the id of the user that made the post

followers (id, follower_id, following_id)

  • id is the auto-generated id
  • follower_id is the user who is doing the following
  • following_id is the user that is being followed

So, being new to sql as well, I tried to test some sql queries against my db with this statement:

SELECT * FROM tweets 
WHERE user_id IN
(SELECT following_id FROM followers WHERE follower_id = 1)  <--- this 1 is just a magic number to test out the query

In this query, I'm trying to find all the tweets of those users that are being followed by user (with id of 1)

My question is sort of two-fold. For the life of me, I can't find out how to make an equivalent find query in cake. Secondly, my sql query involves looking at two tables, so in effect, over two cakephp Models. I'm not sure how to use two models from one controller to construct this find query.


回答1:


$conditionsSubQuery['`followers`.`follower_id `'] = 1;
$dbo = $this->Follower->getDataSource();

$subQuery = $dbo->buildStatement(    
    array(        
        'fields' => array('`followers`.`following_id`'),
            'table' => $dbo->fullTableName($this->Follower), 
           'alias' => 'followers', 
           'limit' => null,  
          'offset' => null, 
           'joins' => array(),  
          'conditions' => $conditionsSubQuery,
            'order' => null,  
          'group' => null    ),

        $this->Follower);



    $subQuery = ' `tweets`.`user_id` IN (' . $subQuery . ') ';

    $subQueryExpression = $dbo->expression($subQuery);

   $conditions[] = $subQueryExpression;

   $this->Tweet->find('all', compact('conditions'));


来源:https://stackoverflow.com/questions/7642726/cakephp-find-statement-for-a-sql-query-involving-two-models

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!