简体   繁体   English

在 laravel 中返回多对多关系结果,如果不存在则返回 null

[英]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 ID
title标题
teachers教师
id ID
name姓名
subject_teacher学科教师
id ID
subject_id主题ID
teacher_id教师编号
semester_id学期编号

this is my code with foreach and it return null if it doesn't exist这是我的 foreach 代码,如果它不存在,它会返回 null

 $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?有没有办法在没有循环的情况下在一行中使用 eloquent 获取每个主题的工作人员,如果不存在则返回 null?

Has has() is to filter the selecting model based on a relationship. has() 是根据关系过滤选择 model 。 So it acts very similarly to a normal WHERE condition.所以它的行为与正常的 WHERE 条件非常相似。 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.如果您只使用 has('relation') ,则意味着您只想获取在此关系中至少具有一个相关 model 的模型。

Example:例子:

User > hasMany > Post用户 > hasMany > 发布

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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