我在用户模型和钱包模型之间存在多对多关系:
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
内部 在wallets
.id
上加入user_wallet
=user_wallet
.wallet_id
user_wallet
.user_usr_id
= 373)
但是这个用户ID中的钱包已经存在于user_wallet
表中:
那么这里出了什么问题?我该如何解决这个问题?
我非常感谢你们对此提出的任何想法或建议......
提前致谢。
【问题讨论】:
【参考方案1】:尝试在关系中提及数据透视表
public function users()
return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
和
public function wallets()
return $this->belongsToMany(Wallet::class,'user_wallet','wallet_id','user_id');
参考:https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
【讨论】:
还是SQLSTATE[42S22]: Column not found: 1054 Unknown column
太好了,谢谢你,但是如何根据wallet_id
获得wallet
名称
钱包名称存储在wallets
表中。我在这个问题中输入了 Migrations 的信息:***.com/questions/68372299/…
@loctoj 因为它是单独的问题。所以我已经更新了那个问题
嘿,伙计,我想知道使用相同键以相同顺序定义的两个 belongsToMany 关系是否正确?