【问题标题】:Pivot table select in LaravelLaravel 中的数据透视表选择
【发布时间】:2015-02-14 01:17:58
【问题描述】:

我为我的表 userscourses 创建了一个数据透视表。

一个用户可以有很多课程,一个课程可以有很多课程。所以,

Course.php

 public function user(){
       return $this->hasMany('User');
    }

User.php

public function courses(){
    return $this->hasMany('Course');
}

当我尝试调用以下查询时,出现错误。

$user = User::where('id', Auth::user()->id)->first();
$courses = $user->courses->get();


错误:

SQLSTATE [42S22]: Column not found: 1054 Champ 'courses.user_id unknown in where clause (SQL: select * from `` Where courses` courses`.`user_id` = 3)

可能是什么问题?我做得对吗?

【问题讨论】:

    标签: php sql laravel laravel-4


    【解决方案1】:

    你必须返回关系。您还需要使用belongsToMany() 进行多对多关系。

    public function user(){
        return $this->belongsToMany('User');
    }
    

    public function courses(){
        return $this->belongsToMany('Course');
    }
    

    ⇒ Laravel Docs

    【讨论】:

    • 我仍然收到错误SQLSTATE [42S22]: Column not found: 1054 Champ 'courses.user_id unknown in where clause (SQL: select * from `` Where coursescourses.user_id` = 3)`
    • 您能否重新格式化错误消息或将其添加到您的问题中?这样读起来有点难。
    • 而引用user.id的外键叫做user_id?
    • dd($users) 返回数组 (size=3) 和其他详细信息。
    • 好的。并获取所有课程? (我真的被select * from '' 激怒了,感觉这就是问题所在)
    【解决方案2】:

    您应该使用$user = User::with('courses')->where('id', Auth::id())->first();,它将在一行中完成您的代码。

    然后您可以使用$user->courses 作为数组来访问这些课程。

    请注意,Auth::id() 等同于 Auth::user()->id

    编辑:您应该对课程使用以下功能:

    public function user()
    {
       return ($this->belongsToMany('User'));
    }
    

    【讨论】:

    • SQLSTATE [42S02]:未找到基表或视图:1146 表 'learningnew.user_user' 不存在(SQL:选择 * users,`as user_user.user_idpivot_user_id` 来自`users`内。```我们加入user_user`users.id` = ``其中user_user.user_id`user_user.user_id`在(3))
    • 您必须使用我在您的课程课程中发布的功能,而不是更改您的用户课程中的功能。抱歉,如果不清楚。
    • 我做到了。发生此错误:SQLSTATE [42S22]: Column not found: 1054 Champ 'courses.user_id unknown in where 子句(SQL: select * from ``Where courses` course.user_id` in (3))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2018-04-10
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多