简体   繁体   English

Laravel 5.8:如何在多对多关系中显示数据透视表的列信息

[英]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.

相关问题 Laravel - 使用额外列保存到多个与多个关系的数据透视表 - Laravel - Saving to pivot table in many to many relationship with extra column 多对多关系在Laravel中检索连接到数据透视表的列 - Many to many relationship retrieve a column connected to pivot table in Laravel 如何基于数据透视表信息删除多对多关系 - How to remove a many-to-many relationship based on the Pivot Table information 如何访问数据透视表的数据(多对多关系laravel) - How to access data of a pivot table ( many to many relationship laravel ) 如何通过 pivot 表中的列过滤多对多关系 - How to filter a many to many relationship by a column in pivot table 如何在 Laravel 5.8 中基于多对多关系查找数据 - How to find data based on Many To Many relationship in Laravel 5.8 如何为一对多关系Laravel创建关联(在数据透视表中)? - How to create association (in pivot table) for one to many relationship Laravel? Laravel L5.5在“多对多”关系中无法访问数据透视表 - Laravel L5.5 No access to pivot table in “Many to many” relationship Laravel - 根据数据透视表中的字段显示具有多对多关系的字段 - Laravel - Displaying fields with many to many relationship according field in pivot table Laravel属于ToMany以多对多关系在数据透视表ID上插入&#39;0&#39;? - Laravel belongsToMany inserting '0' on pivot table ids in a many to many relationship?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM