Laravel中如何通过模型关联获取指定教师的科目名称?
Laravel 模型关联实现查询教师关联学科名称
1. 定义模型及关联关系
先创建对应两张表的模型,并配置关联逻辑:
TeacherSubject 模型(对应teacher_subject表)
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class TeacherSubject extends Model { // 指定表名(模型名复数与表名不一致时需要) protected $table = 'teacher_subject'; // 允许批量赋值的字段 protected $fillable = ['teacher_token', 'subject_token']; // 关联Subject模型,通过subject_token字段匹配 public function subject(): BelongsTo { return $this->belongsTo(Subject::class, 'subject_token', 'subject_token'); } }
Subject 模型(对应subject表)
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; class Subject extends Model { protected $table = 'subject'; protected $fillable = ['subject_token', 'subject_name']; // 反向关联TeacherSubject,可选定义 public function teacherSubjects(): HasMany { return $this->hasMany(TeacherSubject::class, 'subject_token', 'subject_token'); } }
2. 控制器中查询数据
有两种常用的查询方式:
方式一:从TeacherSubject出发查询
namespace App\Http\Controllers; use App\Models\TeacherSubject; class YourController extends Controller { public function getTeacherSubjects() { // 获取teacher_token为1的所有学科名称 $subjectNames = TeacherSubject::where('teacher_token', 1) ->with('subject') // 预加载关联,避免N+1查询问题 ->get() ->pluck('subject.subject_name') // 提取学科名称字段 ->unique() // 去重(如果存在重复关联记录) ->values(); // 重新整理数组索引 return $subjectNames; } }
方式二:从Subject模型反向查询
如果想直接从学科模型入手筛选:
$subjectNames = Subject::whereHas('teacherSubjects', function ($query) { $query->where('teacher_token', 1); })->pluck('subject_name');
关于关联类型的说明
由于你没有单独的教师表,无法使用Laravel原生的多对多关联(多对多要求必须有两个主体模型+中间表)。这里用BelongsTo+HasMany的关联组合完全能满足需求,本质是通过teacher_subject这个中间表,把教师标识(teacher_token)和学科关联起来。
如果后续新增了teachers表(包含teacher_token字段),可以改成标准的多对多关联:
- 在Teacher模型中定义:
public function subjects(): BelongsToMany { return $this->belongsToMany(Subject::class, 'teacher_subject', 'teacher_token', 'subject_token'); } - 在Subject模型中定义反向关联:
public function teachers(): BelongsToMany { return $this->belongsToMany(Teacher::class, 'teacher_subject', 'subject_token', 'teacher_token'); }
内容的提问来源于stack exchange,提问作者coder
相关产品推荐
相关产品推荐

