问题描述
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_id
为 pivot_user_usr_id
,
user_wallet
.wallet_id
作为 pivot_wallet_id
来自 wallets
内部
在 user_wallet
上加入 wallets
。id
= user_wallet
.wallet_id
其中
user_wallet
.user_usr_id
= 373)
但是这个用户 ID 中的钱包已经存在于 user_wallet
表中:
所以这里出了什么问题?我该如何解决这个问题?
我非常感谢你们对此的任何想法或建议......
提前致谢。
解决方法
尝试在关系中提及数据透视表
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