我怎样才能以cakephp-3的方式编写这个查询?

时间:2016-02-12 08:45:20

标签: php sql cakephp cakephp-3.0

原始SQL查询:

SELECT *
FROM
  (SELECT p.id,
          p.title,
          p.mark,

     (SELECT max(created)
      FROM comments c
      WHERE c.post_id=p.id
        AND c.mark=1) AS latest_at
   FROM posts p) AS Post
WHERE Post.latest_at IS NOT NULL
ORDER BY latest_at DESC LIMIT 10

我有这两个表:

$postsTable = TableRegistry::get('Posts');
$comments = TableRegistry::get('Comments');

我用cakephp-3方式做了内部查询:

SELECT p.id,
       p.title,
       p.mark,
       (SELECT max(created)
          FROM comments c
          WHERE c.post_id=p.id AND c.mark=1) AS latest_at
       FROM posts p

Cakephp-3方式内部sql与cakephp-3 querybuilder(下面的查询是否正确?):

        $subquery = $comments->find();
        $subquery->select([$subquery->func()->max('created')])
                ->from(['c'=>'comments'])
                ->where(['c.post_id=p.id','mark=1']);

        $pquery = $postsTable->find()
        ->select(['p.id','p.title','p.mark','latest_at'=>$subquery])
        ->from(['p'=>'posts']);

如何以cakephp-3方式编写外部选择查询? (select * from(derived table))

提前致谢。任何答案都将受到高度赞赏。

3 个答案:

答案 0 :(得分:3)

要直接回答您的问题,这是如何在另一个查询的from部分中使用子查询:

$query = $this->MyTable->connection()->newQuery();
$query->select('*')->from(['Post' => $subqueryObject])->fetchAll('assoc');

这将返回结果数组,如果你知道它应该保持什么类型的实体,那么这样做:

$query = $this->Posts
    ->find()
    ->select($listOfFields)
    ->from(['Posts' => $subqueryObject], true)
    ->toArray();

答案 1 :(得分:1)

对于一个非常简单的问题(即获得最新评论的帖子),这是一个非常复杂的解决方案。

更好的查询是:

 select posts.* from posts join comments on (comments.post_id = posts.id) group by posts.id order by comments.created desc limit 1

执行此查询的ORM方式是:

$post = $postsTable
    ->find()
    ->select(['Posts.id', 'Posts.title', 'Posts.mark', 'Comments.created'])
    ->leftJoinWith('Comments', function ($q) {
        return $q->where(['Comments.mark' => true]);
    }))
    ->group(['Posts.id'])
    ->order(['Comments.created' => 'desc'])
    ->first();

答案 2 :(得分:-1)

对于特殊情况,cakephp允许您编写RAW SQL并保持在cakephp方式内。只需在模型中创建一个函数,您就可以通过将查询放在$this->query("...") 中来编写该查询。

示例(模型中):

public function getPosts(){
      $this->query("SELECT * FROM Posts AS Post"); //put complext query here
}

然后在Controller:

$posts = $this->Post->getPosts();