Laravel通过模型优化查询:获取指定年级的Practice对象
直接通过Laravel模型实现关联查询
第一步:定义模型间的关联关系
先确保各模型已正确设置关联:
Practice模型
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Practice extends Model { // Practice属于一个Section public function section() { return $this->belongsTo(Section::class); } }
Section模型
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Section extends Model { // Section属于一个Book public function book() { return $this->belongsTo(Book::class); } }
Book模型
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Book extends Model { // Book属于一个Grade public function grade() { return $this->belongsTo(Grade::class); } }
第二步:使用Eloquent直接查询Practice对象
通过whereHas方法基于关联模型的条件过滤记录,无需二次查询即可直接获取Practice模型实例:
$grade = 9; // 示例年级 $practiceCode = 'xxx'; // 目标code值 $teacher = auth()->user(); // 示例获取当前教师 $practiceObject = Practice::where('teacher_id', $teacher->id) ->where('code', $practiceCode) ->whereHas('section.book', function ($query) use ($grade) { $query->where('grade_id', $grade); }) ->first();
可选:预加载关联模型
如果后续需要访问关联的Section、Book或Grade数据,可添加with方法预加载,避免N+1查询问题:
$practiceObject = Practice::with('section.book.grade') ->where('teacher_id', $teacher->id) ->where('code', $practiceCode) ->whereHas('section.book', function ($query) use ($grade) { $query->where('grade_id', $grade); }) ->first();
内容的提问来源于stack exchange,提问作者rafig khiyavi
相关产品推荐
相关产品推荐

