php - 如何使用eloquent根据表列和hasMany关系的计数返回记录

标签 php mysql laravel eloquent

我使用的是 Laravel 5.1。我有两个模型

articles
authors

我想查找已发表或有两位以上作者的文章。用 eloquent 做到这一点的最简单方法是什么?

$pub_articles = Articles::where('published',1)->get(); //get articles that are published

我的猜测是这样的

$articles = Articles::where('published',1)
               ->orWhere(Articles->authors::count(),'>',2);

在 SQL 中可能会这样完成

select a.id, a.published from articles a inner join authors au on a.id = au.article_id where a.published = 1 group by a.id, a.published having count(*) > 2

最佳答案

你尝试过has方法吗?

Articles::has('authors', '>', 1)->where('published',1)->get();

关于php - 如何使用eloquent根据表列和hasMany关系的计数返回记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37447417/

相关文章:

php - file_get_contents 接收 cookie

mysql - 范围与用于查找的邮政编码列表?

php - 为什么 "@foreach($pastRegistrations as $pastRegistration)"也返回结果?

mysql - 插入子表时外键失败(引用复合唯一索引)

php - 将 PHP 变量传递给 onLoad (JS)

php - yii 在删除创建表单中的标准侧边栏后删除剩余代码

php - 如何使电子邮件更新数据库?

PHPunit:测试问题

php - 拉维 |如何确认正在使用哪个缓存驱动程序?

php - 脚本处理多个项目但不处理一个