Search code examples
phplaravelmany-to-manylaravel-5.8laravel-relations

Laravel 5.8: Column not found: 1054 Unknown column error in Many To Many relationship


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 as pivot_user_usr_id, user_wallet.wallet_id as pivot_wallet_id from wallets inner join user_wallet on wallets.id = user_wallet.wallet_id where user_wallet.user_usr_id = 373)

However the wallet within this user id exists already at user_wallet table:

enter image description here

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.


Solution

  • 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