CakePHP find语句用于涉及两个模型的sql查询 [英] CakePHP find statement for a sql query involving two models

查看:255
本文介绍了CakePHP find语句用于涉及两个模型的sql查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的蛋糕,我正在做一个类似twitter的克隆。此时,我有3个表:

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

用户(ID,名称)


  • id是自动生成的ID

  • 用户名称

tweets(id,content,user_id)


  • id是自动生成的ID

  • 内容是tweet的文本

  • user_id是发布帖子的用户的ID

关注者(id,follower_id,follow_id)


  • id是自动生成的ID

  • follower_id是执行以下操作的用户

  • follow_id是正在关注的用户

因此,作为sql的新手,我试图测试一些sql使用此语句查询我的数据库:

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

在此查询中,我尝试查找用户(ID为1)跟踪的所有用户的推文

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

我的问题是sort的两倍。对于我的生活,我不知道如何使一个等价的查询查询在蛋糕。其次,我的sql查询涉及查看两个表,所以实际上,两个cakephp模型。我不知道如何使用两个模型从一个控制器来构造这个查询查询。

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.

推荐答案

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

这篇关于CakePHP find语句用于涉及两个模型的sql查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆