【问题标题】:Laravel 5.8: How to show a column information of a pivot table in Many To Many relationshipLaravel 5.8:如何在多对多关系中显示数据透视表的列信息
【发布时间】:2021-07-14 05:59:08
【问题描述】:

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

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

但是钱包余额数据没有出现(因为它在数据透视表中,而不是wallets 表中)。

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

【问题讨论】:

    标签: php laravel laravel-5.8


    【解决方案1】:

    使用withPivot 并提及其他列名

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

    然后在视图中

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

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 2019-09-27
      • 2023-02-05
      • 2018-09-23
      • 1970-01-01
      • 2021-05-08
      • 2015-02-11
      • 1970-01-01
      • 2019-10-19
      相关资源
      最近更新 更多