只使用模型而不是直接访问数据库来获取表中外键与主键匹配的所有行的任何方法


Any way to get all rows of a table where the foreign key matches the primary key using only models rather than accessing the database directly?

我有两个模型:User和Lesson。课程通过课程中的user_id外键与用户绑定。我想说"给我用户8的所有课程",但我能做到这一点的唯一方法是通过DB类

$lessons = DB::table('lessons')->where('user_id','=',8)->get();

有办法做这样的事情吗?

$lessons = Lesson::all()->where('user_id','=',8);

或者(甚至更好)

$lessons = User::find(8)->lessons();

只是想知道,因为后两种方式更有意义。只是想知道!

您可以尝试以下操作:

$lessons = Lesson::where('user_id', 8)->get(); // '=' is optional

user带课程:

$userWithLessons = User::with('lessons')->find(8);

User::find(8)->lessons;也会起作用,但热切加载(with('lessons'))更好。

另一种依赖于users表中id的方法:

// pass the id in $id
$lessons = Lesson::with('user')->whereHas('user', function($q) use ($id){
    $q->where('id', $id);
})->get();

更新:您可以尝试此

// pass the id in $id
$id = 8; // user id
$lesson71 = Lesson::with('users')->whereHas('users', function($q) use ($id){
    $q->where('id', $id);
})->find(71);