【问题标题】:Laravel 5.8: Column not found: 1054 Unknown column error in Many To Many relationshipLaravel 5.8:未找到列:1054 多对多关系中的未知列错误
【发布时间】:2021-09-23 02:24:48
【问题描述】:

我在用户模型和钱包模型之间存在多对多关系:

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表中:

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

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

提前致谢。

【问题讨论】:

    标签: php laravel many-to-many laravel-5.8 laravel-relations


    【解决方案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 的信息:stackoverflow.com/questions/68372299/…
    • @loctoj 因为它是单独的问题。所以我已经更新了那个问题
    • 嘿,伙计,我想知道使用相同键以相同顺序定义的两个 belongsToMany 关系是否正确?
    猜你喜欢
    • 2017-11-07
    • 2021-10-02
    • 2016-01-11
    • 2015-02-22
    • 2020-05-13
    • 1970-01-01
    • 2015-05-25
    • 2021-08-08
    • 2019-11-11
    相关资源
    最近更新 更多