[英]Laravel 5.8: How to show a column information of a pivot table in Many To Many relationship
I have a Many To Many relationship between User Model & Wallet Model:我在用户模型和钱包模型之间有一个多对多的关系:
Wallet.php :钱包.php :
public function users() {
return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
}
And User.php :和User.php :
public function wallets() {
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id');
}
And the pivot table
of this relationship goes like this:这种关系的
pivot table
是这样的:
So I can properly show Wallet name at the Blade:所以我可以在 Blade 正确显示钱包名称:
@forelse($user->wallets as $wallet)
<tr>
<td>
{{ $wallet->name }}
</td>
<td>
{{ $wallet->balance }}
</td>
</tr>
@empty
<td colspan="5" class="text-center">
No wallet exist
</td>
@endforelse
But the wallet balance data does not appear (because it's in the pivot table and not the wallets
table).但是钱包余额数据没有出现(因为它在数据透视表中而不是
wallets
表中)。
So how to show this custom column in this case?那么在这种情况下如何显示这个自定义列呢?
use withPivot
and mention additional column name使用
withPivot
并提及附加列名称
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}
then in view然后在视图中
<td>{{ $wallet->pivot->balance }}</td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.