【问题标题】:CakePHP find statement for a sql query involving two models涉及两个模型的 sql 查询的 CakePHP find 语句
【发布时间】:2011-10-04 02:30:55
【问题描述】:

我是蛋糕新手,我正在练习类似 Twitter 的克隆。此时,我有 3 个表:

users (id, name)

  • id是自动生成的id
  • 用户名

tweets (id, content, user_id)

  • id是自动生成的id
  • 内容是推文的文本
  • user_id 是发帖用户的 ID

followers (id, follower_id, following_id)

  • id是自动生成的id
  • follower_id 是执行以下操作的用户
  • following_id 是被关注的用户

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

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)

我的问题有两个方面。对于我的生活,我不知道如何在 cake 中进行等效的查找查询。其次,我的 sql 查询涉及查看两个表,因此实际上超过了两个 cakephp 模型。我不确定如何使用一个控制器中的两个模型来构造这个查找查询。

【问题讨论】:

标签: php sql cakephp find


【解决方案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'));

【讨论】:

  • 谢谢!我试过这个,但我得到了这个错误: SQL 错误:1054:'IN/ALL/ANY 子查询'中的未知列'tweets.user_id' 我验证了这些是正确的数据库和表名。会不会有其他原因导致这种情况发生?
  • 我通过以下行修复了它: $subQuery = 'user_id IN (' . $subQuery . ') ';谢谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 2013-04-18
  • 1970-01-01
相关资源
最近更新 更多