I have a Many To Many relationship between User Model & Wallet Model:
Wallet.php
:
public function users()
{
return $this->belongsToMany(User::class);
}
And User.php
:
public function wallets()
{
return $this->belongsToMany(Wallet::class);
}
And I want to get wallet list of a single user like this:
@forelse($user->wallets as $wallet)
<tr>
<td>{{ $wallet->id }}</td>
</tr>
@empty
<td colspan="5" class="text-center">No wallet exist</td>
@endforelse
But I get this error somehow:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_wallet.user_usr_id' in 'field list' (SQL: select
wallets
.*,user_wallet
.user_usr_id
aspivot_user_usr_id
,user_wallet
.wallet_id
aspivot_wallet_id
fromwallets
inner joinuser_wallet
onwallets
.id
=user_wallet
.wallet_id
whereuser_wallet
.user_usr_id
= 373)
However the wallet within this user id exists already at user_wallet
table:
So what's going wrong here? How can I fix this issue?
I would really appreciate any idea or suggestion from you guys about this...
Thanks in advance.
Try Mentioning pivot table in relationship
public function users()
{
return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
}
and
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','wallet_id','user_id');
}
Ref:https://laravel.com/docs/8.x/eloquent-relationships#many-to-many