拉拉维尔蒙戈多对多关系在哪里不起作用



我有两个 mongo 文档,它们在多对多关系中相互关联。一个叫律师,另一个叫法律案例。

我的律师模式有:

public function cases()
{
return $this->belongsToMany('AppLawCase');
}

我的 LawCase 模型有:

public function lawyers()
{
return $this->belongsToMany('AppLawyer');
}

我所要做的就是找到有一定类别法律案件的律师。

$lawyers = AppLawyer::whereHas('cases', function($q){
$q->where('category', '=', 'DUI');
})->get();

即使我有具有"DUI"类别的法律案例文件,这也没有任何意义。

当我这样做时

$lawyers = AppLawyer::with('cases')->get();

这给了我一个结果集。只是对哪里有一些问题。我错过了什么?

我尝试研究这个问题,但看起来其他人可能有类似的问题:

Laravel + Jenssegers\Mongodb:"WhereHas"和"Has"返回空集合

如果 wherehas 不起作用,您将如何做到这一点?

更新:

My Lawyer Document
{ 
"_id" : ObjectId("5945f88c9a89205aae0efea8"), 
"full_name" : "Some Name ", 
"active" : true, 
"updated_at" : ISODate("2017-06-18T03:50:36.849+0000"), 
"created_at" : ISODate("2017-06-18T03:50:36.849+0000"), 
"law_case_ids" : [
"5945f88c9a89205aae0efea9", 
"5945f88c9a89205aae0efeac", 
"5945f8b59a89205aae0f3f81", 
"5955d0ff9a89200a57340db8"
]
}

我的法律案例文件

{ 
"_id" : ObjectId("5945f88c9a89205aae0efe9a"), 
"category" : "DUI", 
"updated_at" : ISODate("2017-06-18T03:50:36.825+0000"), 
"created_at" : ISODate("2017-06-18T03:50:36.821+0000"), 
"lawyer_ids" : [
"5945f88c9a89205aae0efe99"
]
}

这是正确的方法,这将返回有符合类别DUI的案件的律师。

$lawyers = AppLawyer::with(['cases'=> function($q){
$q->where('category', '=', 'DUI');
}])->get();
return $this->belongsToMany('AppLawCase');

将外键放在您的关系中

return $this->belongsToMany('AppLawCase', 'foreign_key');

显然转换是不正确的(如果它甚至存在?
因此,请手动设置密钥:

案例型号:

public function lawyers()
{
return $this->belongsToMany('AppLawyer', null, 'case_ids', 'lawyer_ids');
}

律师模式:

public function cases()
{
return $this->belongsToMany('AppLawCase', null, 'lawyer_ids', 'case_ids');
}

请注意,我们需要双向关系含义layer_ids在案例模型中,case_ids在律师模型(数据库条目)中。

使用附加应正确更新两个表,例如:

$lawyer->cases()->attach($case->id)

(我们需要两个表中的相应 ID 才能正确显示关系)

最新更新