例如,table1和table2,并通过枢轴表连接在一起
table1: {
pivot: {
pivot_value1: 1
},
table2: {
....
}
}代码:
table1::with(['table2' => function($q) {
$q->where('table2_property1', 'pivot_value1') // <= how to access pivot value?
}])发布于 2017-04-20 05:03:21
在您定义关系的模型中,我们需要在建立关系时使用withPivot()函数,例如在您的table1模型中;
class Table1 {
public function table2() {
return $this->belongsToMany('App\Table2')->withPivot('column1', 'column2');
}
} 通常在枢轴表中有三个cloumns,另外,如果我们添加了额外的列(比如column1 & column2 ),我们就可以得到这些额外的cloumns的值。在这里,column1 & column2是枢轴表中访问这些列值的附加列:
$table1 = Table1::find(1);
foreach ($table1->table2 as $table) {
echo $table->pivot->column1;
echo $table->pivot->column2;
}另一种使用查询生成器的解决方案:
Table1::whereHas('table2', function($q) {
$q->where('table2_property1', 'pivot_value1');
})
->get();上面的代码只是一个例子,您可以修改它来完善您的需求。希望能帮上忙。
https://stackoverflow.com/questions/43505810
复制相似问题