简体   繁体   中英

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?

I have two models: User and Lesson. Lessons are tied to users through a user_id foreign key in Lessons. I want to say "give me all lessons for user 8", but the only way I've been able to accomplish that is by going through the DB class

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

Is there a way to do something like this?

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

or (even better)

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

Just wondering because the latter two ways make more sense. Just wondering!

You may try something like this:

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

Or user with lessons:

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

Also User::find(8)->lessons; will work but eager loading ( with('lessons') ) is better.

Another way depending on id in users table:

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

Update: You may try this

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM