简体   繁体   中英

return many to many relation result in laravel and return null if it doesn't exist

i have a relation between tables subjects and teachers (many to many)

subjects
id
title
teachers
id
name
subject_teacher
id
subject_id
teacher_id
semester_id

this is my code with foreach and it return null if it doesn't exist

 $subjects = Subject:all();
 foreach ($subjects as $subject){
            $subject->staff = $subject->staffSubjects()->wherePivot('semester_id',$semester->id)->first();
        }

is there a way to get the staff of each subject with eloquent in one line without a loop and if it doesn't exist return null?

Has has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get()

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