Laravel 5.8: 如何在多对多关系中显示主元 table 的列信息

Laravel 5.8: How to show a column information of a pivot table in Many To Many relationship

我在用户模型和钱包模型之间存在多对多关系:

Wallet.php:

public function users() {
    return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
}

User.php:

public function wallets() {
    return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id');
}

而这段关系的pivot table是这样的:

所以我可以在 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

但是钱包余额数据没有出现(因为它在枢轴 table 而不是 wallets table)。

那么在这种情况下如何显示这个自定义列呢?

使用 withPivot 并提及其他列名称

public function wallets()
{
    return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}

然后在视图中

  <td>{{ $wallet->pivot->balance }}</td>