Php 拉威尔口若悬河,关系何在

Php 拉威尔口若悬河,关系何在,php,laravel,laravel-5,eloquent,where,Php,Laravel,Laravel 5,Eloquent,Where,我有一个课程模型,它有很多帮助模型 public函数帮助(){ 返回$this->hasMany(Help::class); } 现在的问题是,当我试图在某个特定的课程中获得帮助时,我遇到了一些小问题 $help=$course->help() ->where(['from_id'=>497])->或where(['to_id'=>497])->get(); 当我尝试获得帮助时,结果是正确的当然1: “数据”:[ { “id”:12, “留言”:“你好”, “from_id”:497, “t

我有一个课程模型,它有很多帮助模型

public函数帮助(){
返回$this->hasMany(Help::class);
}
现在的问题是,当我试图在某个特定的课程中获得帮助时,我遇到了一些小问题

$help=$course->help()
->where(['from_id'=>497])->或where(['to_id'=>497])->get();
当我尝试获得帮助时,结果是正确的当然1:

“数据”:[
{
“id”:12,
“留言”:“你好”,
“from_id”:497,
“to_id”:1,
“课程id”:1,
},
{
“id”:108,
“留言”:“你好…”,
“from_id”:1,
“to_id”:497,
“课程id”:1,
},
{
“id”:197,
“消息”:“确定正文”,
“from_id”:1,
“to_id”:497,
“课程id”:1,
}
]
但是,当我尝试获取任何没有帮助的课程的帮助时,它会返回
或where
字段,而忽略
$course->help()

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

“数据”:[
{
“id”:108,
“留言”:“你好…”,
“from_id”:1,
“to_id”:497,
“课程id”:1,
},
{
“id”:197,
“消息”:“确定正文”,
“from_id”:1,
“to_id”:497,
“课程id”:1,
}
]

问题出在
或where
。要生成正确的查询,您应该将条件包装到附加闭包中

$helps = $course->helps()->where(function($q) {
    $q->where('from_id', 497)->orWhere('to_id', 497)
})->get();
用闭包换行将()添加到所需位置

现在你将有一个条件,
A和(B或C)
,在你有
A和B或C之前,
(A和B)或C的真正含义是什么


我还从
where
中删除了数组语法,以保持其更清晰。

问题在于
或where
。要生成正确的查询,您应该将条件包装到附加闭包中

$helps = $course->helps()->where(function($q) {
    $q->where('from_id', 497)->orWhere('to_id', 497)
})->get();
用闭包换行将()添加到所需位置

现在你将有一个条件,
A和(B或C)
,在你有
A和B或C之前,
(A和B)或C的真正含义是什么

我还从
中删除了数组语法,以保持其更清晰。

尝试以下操作:

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

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

您是否尝试在何处添加
课程id
clause@DeepakPatel它是这样工作的:
$Help=Help::where('course\u id','=',$course->id)->where('from\u id','=','user->id)->where('course\u id','=','course->id)->where('to\u id','=','user->id)->get()但是为什么我的方式是错误的?'$help=$course->help()->where(['from\u id'=>497])->或者where(['to\u id'=>497])->get();'仅获取由您指定而不是由
课程id
指定的
表单id
到id
的数据。您可以将此$course->与(['help'=>函数($q){$q->where(…);}])->where(函数($q){$q->where(['from\id'=>497])->或where(['to\id'=>497})一起使用)您是否尝试在何处添加
课程id
clause@DeepakPatel它是这样工作的:
$Help=Help::where('course\u id','=',$course->id)->where('from\u id','=','user->id)->where('course\u id','=','course->id)->where('to\u id','=','user->id)->get()但是为什么我的方式是错误的?'$help=$course->help()->where(['from\u id'=>497])->或者where(['to\u id'=>497])->get();'仅获取由您指定而不是由
课程id
指定的
表单id
到id
的数据。您可以将此$course->与(['help'=>函数($q){$q->where(…);}])->where(函数($q){$q->where(['from\id'=>497])->或where(['to\id'=>497})一起使用)