CakePHP find statement for a sql query involving t

2019-07-30 07:17发布

问题:

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