2017-10-20 110 views
0

我试图用查找表使用2个表之间的“belongsToMany”关系来定义多对多关系。这些都是我的表:Laravel belongsToMany不工作

encounter_templates(EncounterTemplate模型)

  • ID
  • TEMPLATE_NAME
  • ...(更多不相干的colums)

encounter_forms(EncounterForm模型)

  • id
  • FORM_NAME
  • ...(更多不相干的colums)

encounter_templates_forms(EncounterTemplateForm模型)

  • ID
  • template_id
  • form_id

在EncounterTemplate模型我试图附加的属于它形成了一个列表,所以我有以下内容的形式()函数:

public function forms() { 
    return $this->belongsToMany('\App\EncounterForm', 'encounter_templates_forms', 'template_id', 'form_id'); 
} 

但是它返回一个空的对象。我可以通过使用以下代替工作得到它的工作:

$forms = \App\EncounterTemplateForm::where("template_id",$this->id) 
    ->join("encounter_forms", "encounter_templates_forms.form_id","=","encounter_forms.id") 
    ->get(); 

return $forms; 

但我想知道我做错了我的关系声明。如果可以的话,我宁愿按照“适当”的Laravel方式来做。希望有任何见解。

编辑:如果我运行EncounterTemplate ::发现(1) - >形式() - > toSql()我得到以下查询:

select * from `encounter_forms` inner join `encounter_templates_forms` on `encounter_forms`.`id` = `encounter_templates_forms`.`form_id` where `encounter_templates_forms`.`template_id` = 1 

它返回预期的结果...所以也许问题为进一步向下游...

回答

0

所以进一步下游我动态调用forms()方法。事实证明,我需要调用一个 - > get(),因为它显然是forms()返回查询生成器实例而不是模型结果。对于任何未来的人感兴趣,这是我的工作代码看起来像:

$record = $model::find($id); 
$include = $request->input("include"); 
$result_array = $record->toArray(); 

if ($include) { 
    $includes = json_decode($include); 

    foreach ($includes as $child_model) { 
     $child = $record->$child_model(); 
     $result_array[$child_model] = $child->get(); //where $child == 'forms' 
    } 
} 

return $record_array; 

感谢您的疑难解答詹姆斯的帮助!您的意见帮助我缩小了问题的根源。

0

看起来你们的关系仅仅是一个小关,从文档:

...第三个参数是要定义关系的模型的外键名称,而第四个参数是要加入的模型的外键名称

因为这样的参数是这样的:

  1. 要链接到
  2. 是连接这些记录
  3. 在连接表中的字段的引用当前型号名称表的名称另一种模式
  4. 的连接表中的字段引用国外模型

给你要定义在EncounterTemplate模型这种关系目前,第三个参数应该是template_id和第四form_id名称:

public function forms() { 
    return $this->belongsToMany('App\EncounterForm', 'encounter_templates_forms', 'template_id', 'form_id'); 
} 
+0

你是对的文档表明它应该是另一种方式,这是我最初如何尝试它,但不幸的是我尝试了两种变化,似乎都没有工作。我已经编辑了我的帖子来反转列名称(并且再次运行我的代码,并将其颠倒过来以便三重检查我是否会发疯),但它仍然无效。 – user3246127

+0

@ user3246127尝试预览SQL,看看发生了什么'EncounterTemplate :: find(1) - > forms-> toSql();'这里假定你有一个具有表单的模板1。 – James

+0

它返回正确的查询和运行该查询原始返回预期的结果,所以也许问题是在我的项目进一步下游的地方。当我弄明白时,我会更新这个问题! – user3246127

0

试试这个它对我有用。

在模型中添加此

EncounterTemplate模式

public function encounterTemplateForm() 
    { 
     return $this->hasMany(EncounterTemplateForm::class); 
    } 

EncounterForm模式

public function encounterTemplateForm() 
    { 
     return $this->hasMany(EncounterTemplateForm::class); 
    } 

EncounterTemplateForm模式

public function template() 
{ 
    return $this->belongsTo(EncounterTemplate::class, 'template_id', 'id'); 
} 

public function form() 
{ 
    return $this->belongsTo(EncounterForm::class, 'form_id', 'id'); 
}