我正在像下面这样使用laravel eloquent查询数据库。
PostModel::with('images')->where('id', $id)->where('is_active', 1)->paginate(10);
在某些情况下,某些帖子没有图像,因此images
属性的数组为空。我需要知道的是如何丢弃empty array
为images
的结果。我不想运行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