Laravel Eloquent orWhere on relationships

Laravel Eloquent orWhere on relationships

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

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,
        }
    ]

但是当我试图获得任何没有帮助的课程的帮助时,它不是空数组 returns 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,
        }
    ]

问题是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 中删除了数组语法以使其更简洁。

试试这个:

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