繁体   English   中英

laravel 属于拥有 pivot 的表没有获取数据

[英]laravel belongstomany with pivot table doesn't get data

我有 3 张桌子:legalpursuit、guarantors、guarantors_legalpursuit。 我的项目中有多对多关系。 我将legalpursuit_id 保存在legalpursuit / guarantors_id 中,并将它们都保存在guarantors_legalpursuit 中。

我正在使用 laravel 8. 如何显示每个帖子的标签? 如何从 tag_post 表中获取 select 数据? 我使用它如下。 但它没有得到数据。

这是我的 Legalpursuit model:

public function guarantorses()
{
    //return $this->belongsToMany(RelatedModel, pivot_table_name, foreign_key_of_current_model_in_pivot_table, foreign_key_of_other_model_in_pivot_table);
    return $this->belongsToMany(Guarantors::class, 'guarantors_legalpursuit', 'legalpursuit_id', 'guarantors_id');
}

这是我的担保人 model:

    public function legalpursuits()
{
    //return $this->belongsToMany(RelatedModel, pivot_table_name, foreign_key_of_current_model_in_pivot_table, foreign_key_of_other_model_in_pivot_table);
    return $this->belongsToMany(LegalPursuit::class,'guarantors_legalpursuit','guarantors_id', 'legalpursuit_id');
}

这是我的 controller:

    public function edit(LegalPursuit $legalPursuit, $id)
{
    $user           = Auth::user();
    $data           = LegalPursuit::find($id);

    $guarantors     = $data->guarantorses()->orderBy('name')->get();
    $lawyers        = $data->lawyers()->orderBy('name')->get();

    dd($guarantors);

    $filesPursuit   = LegalPursuit::find($id)->files;
    $getLawyersLeft = DB::table('users')->where('user_type', '2')
                                        ->where('active', '1')
                                        ->where('deleted', '0')
                                        ->take('5')
                                        ->get();

    return view('pages.legalpursuit.edit', compact('data', 'getLawyersLeft', 'filesPursuit', 'user'));
}

没有表名不同,它实际上完全遵循;

protected $table    = 'guarantors';

该表的字段如下;

table name; guarantors
field: ID
field: name

pivot 表名称和详细信息;

 table name; guarantors_legalpursuit
id;
guarantors_id
legalpursuit_id



I can also do the adding process successfully as follows.

        $guarantorArray = $request->input('GUARANTORS');
        //$GuarantorsID = Guarantors::find($guarantorArray);
        $data->guarantorses()->attach($guarantorArray);

但我无法提取关系数据。 它没有给出错误。 但是虽然表中有数据,但是数组感觉是空的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM