从 Pivot Table On Model 访问数据
Access Data From Pivot Table On Model
我需要从数据透视表中获取数据 table。
我有 2 个模型:sites、technologies。这 2 个模型通过名为 site_technology 的枢轴 table 关联,此 table 有 2 个名为 col_a 的列我要访问的 、col_b。现在我有这个:
class Site{
public function technologies(){
return $this->hasMany('App\Models\Technology')
}
}
我的问题是,我如何 link 这两个模型,以及如何使用 eloquent 访问那个 piovt table 上的数据?
我经常看到这个问题,我发现最好的方法是使用以下代码。
class Site{
public function technologies(){
return $this->belongsToMany(Technology::class, 'PIVOT_TABLE')->withPivot('column_a', 'column_b')
}
}
这将允许您通过执行此操作来获取数据。
$data = Site::first()->technologies->first()->pivot->column_b
希望对您有所帮助!
我需要从数据透视表中获取数据 table。
我有 2 个模型:sites、technologies。这 2 个模型通过名为 site_technology 的枢轴 table 关联,此 table 有 2 个名为 col_a 的列我要访问的 、col_b。现在我有这个:
class Site{
public function technologies(){
return $this->hasMany('App\Models\Technology')
}
}
我的问题是,我如何 link 这两个模型,以及如何使用 eloquent 访问那个 piovt table 上的数据?
我经常看到这个问题,我发现最好的方法是使用以下代码。
class Site{
public function technologies(){
return $this->belongsToMany(Technology::class, 'PIVOT_TABLE')->withPivot('column_a', 'column_b')
}
}
这将允许您通过执行此操作来获取数据。
$data = Site::first()->technologies->first()->pivot->column_b
希望对您有所帮助!