【问题标题】:Laravel Eloquent orWhere on relationshipsLaravel Eloquent orWhere 关系
【发布时间】:2018-07-21 04:03:06
【问题描述】:

我有一个包含许多帮助模型的课程模型。

public function helps() {
    return $this->hasMany(Help::class);
}

现在的问题是,当我尝试获得特定课程的帮助时,我在哪里和哪里遇到了小问题。

$helps = $course->helps()
    ->where(['from_id' => 497])->orWhere(['to_id' => 497])->get();

当我尝试寻求帮助时结果是正确的,当然 1:

"data": [
        {
            "id": 12,
            "message": "hi there",
            "from_id": 497,
            "to_id": 1,
            "course_id": 1,
        },
        {
            "id": 108,
            "message": "hi ...",
            "from_id": 1,
            "to_id": 497,
            "course_id": 1,
        },
        {
            "id": 197,
            "message": "ok body",
            "from_id": 1,
            "to_id": 497,
            "course_id": 1,
        }
    ]

但是当我尝试获得任何没有帮助的课程的帮助时,它会返回 orWhere 字段而不是空数组,而忽略 $course->helps()

这是没有任何帮助的课程 2 的结果:

"data": [
        {
            "id": 108,
            "message": "hi ...",
            "from_id": 1,
            "to_id": 497,
            "course_id": 1,
        },
        {
            "id": 197,
            "message": "ok body",
            "from_id": 1,
            "to_id": 497,
            "course_id": 1,
        }
    ]

【问题讨论】:

  • 您是否尝试在 where 子句中添加course_id
  • @DeepakPatel 以这种方式工作:$helps = Help::where('course_id', '=', $course->id)->where('from_id', '=', $user->id) ->orWhere('course_id', '=', $course->id)->where('to_id', '=', $user->id)->get(); 但为什么我的方式是错误的?
  • '$helps = $course->helps() ->where(['from_id' => 497])->orWhere(['to_id' => 497])->get() ;'仅获取由您指定的 form_idto_id 的数据,而不是由 course_id 指定的数据
  • 你可以使用这个 $course->with(['helps' =>function($q){ $q ->where(...); }])->where(function( $q){ $q->where(['from_id' => 497])->orWhere(['to_id' => 497]); })

标签: php laravel laravel-5 eloquent where


【解决方案1】:

问题是orWhere。要生成正确的查询,您应该将条件包装到额外的闭包中。

$helps = $course->helps()->where(function($q) {
    $q->where('from_id', 497)->orWhere('to_id', 497)
})->get();

使用闭包将 ( ) 添加到所需位置。

现在您将拥有A AND (B OR C) 和之前A AND B OR C 真正意味着(A AND B) OR C 的条件。

我还从 where 中删除了数组语法,以使其更简洁。

【讨论】:

    【解决方案2】:

    试试这个:

    $helps = $course->helps->where('from_id', 497)->orWhere('to_id', 497);
    

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 2016-08-13
      • 2018-02-09
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多