You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:42:10