【问题标题】:Column not found: 1054 Unknown column issue未找到列:1054 未知列问题
【发布时间】:2020-06-04 11:59:30
【问题描述】:

我有包含 id、名称、时间戳和其他字段的 Account 模型,我有包含 account_id 和 user_id 字段的 AccountUser 模型,我有包含用户 ID 的 User 模型。

我正在尝试使用 $this->hasManyThrough('App\User', 'App\AccountUser')->get(); 按帐户获取用户(帐户有很多用户);但我有一个错误 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.account_user_id' in 'on clause' (SQL: select users.*, account_users.account_id from users inner join account_users account_users.id = users.account_user_id 其中account_users.account_id = 1)。

我不需要'users.account_user_id' 列,但它在查询中,怎么办?谢谢。

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:
    1. 您必须在模型中而不是在查询中定义关系。
    2. 对于这种情况,您应该使用 hasOne 属性
    3. 您必须在模型中指定关系键:
        // In the User class
        public function account()
        {
            return $this->hasOne(UserAccount::class,'account_id','id');
        }
    

    然后调用与

    的关系
    $user->account();
    

    documentation

    【讨论】:

    • 我需要按帐户的用户,而不是按用户的帐户。
    • 同样的事情,只是在 UserAccount 模型中添加 hasOne(User::class,'id','user_id');
    【解决方案2】:

    hasManyThrough(和所有关系一样)有一个默认值,如果你什么都不放:

    hasManyThrough('App\User', 'App\AccountUser')
    

    它从模型名称中获取默认值。

    来自文档:

    传递给 hasManyThrough 方法的第一个参数是 我们希望访问的最终模型,而第二个参数是 中间模型的名称。

    执行时将使用典型的 Eloquent 外键约定 关系的查询。如果您想自定义键 关系,您可以将它们作为第三个和第四个参数传递 到 hasManyThrough 方法。 第三个参数是中间的外键名称 模型。第四个参数是final上的外键名 模型。第五个参数是本地键,而第六个参数 是中间模型的本地键:

    查看文档: https://laravel.com/docs/7.x/eloquent-relationships#has-many-through

    【讨论】:

    • 我有一个错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.account_user_id' in 'on clause' (SQL: select users.*, account_users.@ 987654325@ from users 内部连接 ​​account_users on account_users.id = users.account_user_id where account_users.account_id = 1)
    猜你喜欢
    • 2015-07-05
    • 2015-02-22
    • 2016-04-09
    • 2020-05-13
    • 2019-01-13
    • 2012-08-18
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多