Laravel 5.8:未找到列:多对多关系中的 1054 未知列错误

问题描述

我在用户模型和钱包模型之间有一个多对多的关系:

Wallet.PHP

public function users()
    {
        return $this->belongsToMany(User::class);
    }

还有User.PHP

public function wallets()
    {
        return $this->belongsToMany(Wallet::class);
    }

我想像这样获取单个用户的钱包列表:

@forelse($user->wallets as $wallet)
<tr>
   <td>{{ $wallet->id }}</td>
</tr>
@empty
<td colspan="5" class="text-center">No wallet exist</td>
@endforelse

但我以某种方式收到此错误

sqlSTATE[42S22]:未找到列:1054 未知列 “字段列表”中的“user_wallet.user_usr_id”(sql:选择wallets.*, user_wallet.user_usr_idpivot_user_usr_iduser_wallet.wallet_id 作为 pivot_wallet_id 来自 wallets 内部 在 user_wallet 上加入 walletsid = user_wallet.wallet_id 其中 user_wallet.user_usr_id = 373)

但是这个用户 ID 中的钱包已经存在于 user_wallet 表中:

enter image description here

所以这里出了什么问题?我该如何解决这个问题?

我非常感谢你们对此的任何想法或建议......

提前致谢。

解决方法

尝试在关系中提及数据透视表

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

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

参考:https://laravel.com/docs/8.x/eloquent-relationships#many-to-many