【问题标题】:Two tables and count(*) in Laravel 4Laravel 4中的两个表和计数(*)
【发布时间】:2014-03-30 10:19:58
【问题描述】:

我有两张表,上面有帖子和投票。如何告诉 laravel 从 'votes' 表中计算选票并通过 id 将其与 posts 表连接?

我有如下原始查询:

SELECT *, (SELECT count(*) FROM votes WHERE posts.id = votes.post_id) AS votes FROM posts 
ORDER BY created_at DESC

但是我不能在需要时使用$query->pagination(6)

在刀片之后,我只想使用类似的东西: {{ $posts->votes }} 其中 votes 是 'votes' 表中与 post 相同 id 的行数。

【问题讨论】:

  • 您是否设置了任何模型关系?然后,您可以通过获取 Post(无论是在 foreach 还是 Post::find 等)并执行 $post->votes()->count(); 轻松做到这一点
  • 好的,谢谢你,我做到了,它有效:)

标签: laravel count eloquent


【解决方案1】:

我也有同样的需求,并使用 trait 来创建子查询。

我明白了。 https://github.com/anlutro/laravel-4-core/blob/master/src/ModelTraits/WithRelationCount.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    相关资源
    最近更新 更多