php - Laravel:让 Eloquent 创建嵌套 SELECT 的正确方法

标签 php laravel eloquent

我试图 Eloquent 地生成的查询是

SELECT *, (SELECT COUNT(comment_id) FROM comment AS c WHERE c.approved=true AND c.blog_fk=b.blog_id) AS comment_count FROM blog AS b

这是结果

blog_id |  title            | author       | blog           | image            | tags    | created             | updated             | comment_count
--------|-------------------|--------------|----------------|------------------|---------|---------------------|---------------------|--------------
     21 | A day..           | dsyph3r      | Lorem ipsum... | beach.jpg        | symf... | 2014-12-22 19:14:34 | 2014-12-22 19:14:34 | 2
     22 | The pool ..       | Zero Cool    | Vestibulum ... | pool_leak.jpg    | pool,.. | 2011-07-23 06:12:33 | 2011-07-23 06:12:33 | 10
     23 | Misdirection...   | Gabriel      | Lorem ipsum... | misdirection.jpg | misd... | 2011-07-16 16:14:06 | 2011-07-16 16:14:06 | 2
     24 | The grid ...      | Kevin Flynn  | Lorem commo... | the_grid.jpg     | grid... | 2011-06-02 18:54:12 | 2011-06-02 18:54:12 | 0
     25 | You're either ... | Gary Winston | Lorem ipsum... | one_or_zero.jpg  | bina... | 2011-04-25 15:34:18 | 2011-04-25 15:34:18 | 2

我目前使用 DB::select( DB::raw()) 来运行它,这可能不是执行此操作的正确方法。

问题是什么是使生成这些结果的查询变得 Eloquent 正确方法?

最佳答案

改用这个:http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently

对于嵌套的select/join语句,你需要这样:

$sub = Comment::selectRaw('count(comment_id) as count')
       ->where('approved', '?')
       ->where('comment.blog_fk', '?')
       ->toSql();

Blog::selectRaw(DB::raw("blog.*, ({$sub}) as comment_count"))
       ->setBindings([true, DB::raw('blog.blog_id')], 'select')
       ->get();

或者简单地将所有内容放入selectRaw

关于php - Laravel:让 Eloquent 创建嵌套 SELECT 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28018466/

相关文章:

php - 外键约束的格式不正确。你能帮助我吗?

php - 如何使用 Laravel Eloquent 在 WHERE 条件下减去 2 列

php - 从数据透视表中检索数据并分配给用户查看整个站点

php - Laravel Eloquent 过滤关系按最后一个数据透视记录

php - Laravel 5.1 用户输入文本中的链接/可点击链接

php - 由于小的 JOIN/WHERE 过滤器,PostgreSQL Select 语句非常慢

php - MySQL查询-即使相关表中不存在一个字段,也返回咨询

php - 无法在实时环境中使用 SmtpTransport 使用 SwiftMailer 发送邮件,但可以在本地主机中发送

laravel - 在 Laravel 中正确使用访问器

laravel - 在 Laravel 中查找或创建