如何在Laravel关联中匹配两表字段值并获取指定列结果
Laravel关联查询实现指定列+条件匹配
1. 先确定关联类型
从你的SQL来看,teacher.subject_token = subject.token是关联条件,结合常见业务场景,一个科目对应多个老师,所以关联关系定义为:
- 老师(Teacher)属于某一个科目(Subject):多对一关联
- 科目(Subject)拥有多个老师(Teacher):一对多关联
2. 定义模型关联
Teacher模型(老师)
// app/Models/Teacher.php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Teacher extends Model { protected $table = 'teacher'; // 表名非默认时指定 protected $primaryKey = 'teacher_token'; // 主键非id时指定 // 关联所属科目 public function subject(): BelongsTo { // 参数:关联模型、当前表外键、关联表主键 return $this->belongsTo(Subject::class, 'subject_token', 'token'); } }
Subject模型(科目,可选)
// app/Models/Subject.php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; class Subject extends Model { protected $table = 'subject'; protected $primaryKey = 'token'; // 关联下属老师 public function teachers(): HasMany { return $this->hasMany(Teacher::class, 'subject_token', 'token'); } }
3. 实现你的查询需求
方式一:用Eloquent关联查询
适合需要复用关联逻辑的场景:
$teacher = Teacher::where('teacher_token', '1') ->with(['subject' => function ($query) { // 只获取科目表的指定列,必须包含关联用的token字段 $query->select('token', 'subject_name'); }]) // 只获取老师表的指定列 ->select('teacher_token', 'teacher_name', 'subject_token') ->first(); // 提取最终结果 $result = [ 'teacher_name' => $teacher->teacher_name, 'subject_name' => $teacher->subject?->subject_name ];
方式二:直接用原生Join写法
完全贴近你给出的SQL,适合一次性查询场景:
$result = Teacher::join('subject', 'teacher.subject_token', '=', 'subject.token') ->where('teacher.teacher_token', '1') ->select('teacher.teacher_name', 'subject.subject_name') ->first();
4. 关联类型选择建议
- 按当前需求,用**多对一(BelongsTo)**关联足够,不需要多对多
- 若后续要支持一个老师教多个科目,才需要新增中间表(如
teacher_subject),改用多对多关联
内容的提问来源于stack exchange,提问作者coder
相关产品推荐
相关产品推荐

