如何使用枢轴列返回雄辩模型的集合?例如,用户和大桶之间存在M:N关系。我想检索所有用户数据(使用vats和枢轴列(costOfDelivery),它位于数据透视表user_vat中)。
在我的代码中,我有:
$vats = Vat::whereHas('users', function($query) use ($user) {
$query->where('user_id', $user->id);
})->with('country')
->get();
但这会从大桶和国家/地区返回数据,而不是来自数据透视表" user_vat",如何检索还是costOfDelivery?
答案 0 :(得分:1)
要从数据透视表中检索数据,您必须使用数据透视属性
像这样的东西
foreach($users->roles as $role){
echo $role->pivot->created_at;
}
要返回json,您可以使用{/ 1}}方法,如
toJson()
答案 1 :(得分:0)
<?php
/**
* The model class with the belongsToMany user class relation.
*/
class Vat extends Model
{
public function user()
{
return $this->belongsToMany(\App\User::class)
->withPivot(['cost_of_delivery', /**Specific columns for the pivot.*/]);
}
}
<?php
/*
* Your query (which I think is a little bit complicated that it should be.
*/
$vats = Vat::whereHas('users', function($query) use ($user) {
$query->where('user_id', $user->id);
})->with(['country', 'users'])
->get();
我会用......像:
<?php
$user->load(['vats.country']);
$vats = $user->getRelationValue('vats');
和
$vats->first()->pivot->cost_of_delivery
应该为您提供第一桶的交付成本。