首页 文章

Laravel属于ToMany不工作

提问于
浏览
0

我正在尝试使用查找表的2个表之间的“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模型中,我试图附加一个属于它的表单列表,所以我有一个form()函数,其中包含以下内容:

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 :: find(1) - > forms() - > 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

哪会返回预期的结果......所以问题可能是下游的进一步......

3 回答

  • 0

    因此,我在下游进行动态调用forms()方法 . 事实证明我需要在它上面调用 - > get(),因为它显然是form()返回一个查询构建器实例而不是模型结果 . 对于任何感兴趣的未来人,这就是我的工作代码:

    $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;
    

    感谢帮助解决詹姆斯问题!您的意见帮助我缩小了问题的根源 .

  • 1

    从文档来看,您的关系看起来有点偏差:

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

    因此参数如下:

    • 您要链接到的其他模型

    • 连接这些记录的表的名称

    • 连接表中引用 current 模型的字段的名称

    • 连接表中引用 foreign 模型的字段名称

    鉴于您当前正在 EncounterTemplate 模型上定义此关系,第三个参数应为 template_id ,第四个参数应为 form_id

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

    尝试这个对我有用的 .

    在模型中添加它

    EncounterTemplate model

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

    EncounterForm model

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

    EncounterTemplateForm model

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

相关问题