【问题标题】:How to use '::whereHas()' as a constraint for '::with()' query when using Eloquent?使用 Eloquent 时如何使用 '::whereHas()' 作为 '::with()' 查询的约束?
【发布时间】:2016-01-12 08:50:15
【问题描述】:

我有一个疑问:

Posts::whereHas('comments', function($query){
          $query->where('name', 'like', 'asd');
      })->with('comments')->get();

它返回所有具有名称为“asd”的 cmets 的帖子以及这些帖子的所有 cmets。我可以在 '::whereHas' 中为 'with' 方法使用上述约束,这样它就不会返回所有 cmets,而只返回符合要求的那些?还是我必须复制查询?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您可以创建类似这样的查询,几乎没有重复 :)

    $callback = function($query) {
         $query->where('name', 'like', 'asd');
    }
    Posts::whereHas('comments', $callback)->with(['comments' => $callback])->get();
    

    或者,你可以在这篇文章中点赞Laravel - is there a way to combine whereHas and with

    【讨论】:

    • 不幸的是,当您嵌套 whereHas 查询时,一切都失败了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 2023-03-07
    • 2021-05-25
    • 2016-07-22
    • 1970-01-01
    • 2021-05-28
    相关资源
    最近更新 更多