【问题标题】:How to discard selecting empty relationship items with another table如何丢弃选择与另一个表的空关系项
【发布时间】:2015-07-17 04:54:19
【问题描述】:

我正在使用 laravel eloquent 查询数据库,如下所示。

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

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

【问题讨论】:

    标签: php laravel eloquent relationship


    【解决方案1】:

    阅读 Eloquent 的 has()whereHas() 方法,网址: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

    【讨论】:

    • 非常感谢您的回复 :)。但这不是选择images,而只是选择具有一张或多张图片的帖子
    • 抱歉忘记了('images')
    猜你喜欢
    • 2015-01-02
    • 2015-02-20
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2011-07-13
    • 2019-03-21
    相关资源
    最近更新 更多