如何放弃对另一个表的空关系项的选择


How to discard selecting empty relationship items with another table

我正在像下面这样使用laravel eloquent查询数据库。

PostModel::with('images')->where('id', $id)->where('is_active', 1)->paginate(10);

在某些情况下,某些帖子没有图像,因此images属性的数组为空。我需要知道的是如何丢弃empty arrayimages的结果。我不想运行foreach并删除项目,我正在查询方面寻找解决方案,例如丢弃这些项目的选择。谢谢。

阅读has()whereHas()方法的Eloquent, url: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations(标题:查询关系存在)

解决方案:

PostModel::with('images')->has('images')->where('id', $id)->where('is_active', 1)->paginate(10);

您可以使用join()(这更性能):http://laravel.com/docs/5.1/queries#joins