优化 Laravel 中的模型查询

huangapple go评论132阅读模式
英文:

Optimizing a query in Laravel by model

问题

我有四张表,它们分别是 practicesectionbookgrade
流程是每个练习与某一本书的特定章节相关联,每个章节与一本特定的书相关联,每本书与一个学习级别相关联。

举个例子,解决维恩图的练习是九年级数学书的第一章的一部分。

我想要一个查询,它可以获取与特定年级相关的练习。

我自己在 Laravel 上运行了这个查询:

$grade = 9;  // 举例
$practice = DB::table('practices')
    ->select('practices.id')
    ->where('teacher_id', $teacher->id)
    ->where('code', $practiceCode)
    ->join('sections', 'practices.section_id', '=', 'sections.id')
    ->join('books', 'sections.book_id', '=', 'books.id')
    ->where('books.grade_id', $grade)
    ->first();

但是,我通过这个查询没有得到一个对象,我需要在将其传递给 Blade 视图时将其转换为对象。这是我如何做的:

$practice_id = $practice->id ;
$practiceObject = Practice::find($practice_id);

但如果可能的话,我想使用模型来实现这个查询。感谢您的帮助。

英文:

I have four tables named practice, section, book, and grade.
The flow is that each practice is related to a section of the patch one book, each section to a patch book, and each book to a level of study.

For example, the practice of solving the Venn diagram is part of the first chapter of the ninth grade math book.

I want to have a query that has the practice that are related to a specific grade.

I ran this query on Laravel myself:

$grade = 9;  //Example
$practice = DB::table('practices')
    ->select('practices.id')
    ->where('teacher_id', $teacher->id)
    ->where('code', $practiceCode)
    ->join('sections', 'practices.section_id', '=', 'sections.id')
    ->join('books', 'sections.book_id', '=', 'books.id')
    ->where('books.grade_id', $grade)
    ->first();

But I don't get an object with this query and I have to convert it to an object when I want to send it to the blade view. This is how I did it:

$practice_id = $practice->id ;
$practiceObject = Practice::find($practice_id);

But I want to implement this query using the model if possible. Thank you for your help.

答案1

得分: 1

我会这样做:

首先,在模型中设置关联关系
然后,我会尝试使用'with'和/或'whereHas'方法,像这样:

$practice = Practices::where([
  'teacher_id', $teacher->id,
  'code', $practiceCode
])
->whereHas('sections', function ($query) {
  $query->where('practice_id ...')
})
->with('relations_you_want'...)
->first()

如果你不知道如何做,可以查看这里的文档

希望对你有帮助!😄

英文:

I would do something like this:

First of all set the relations in the models
And then I would try to build something using the 'with' and/or 'whereHas' methods like this:

$practice = Practices::where([
  'teacher_id', $teacher->id,
  'code', $practiceCode
 ])
 ->whereHas('sections', function ($query) {
   $query->where('practice_id ...')
 })
 ->with('relations_you_want'...)
 ->first()

If you don't know how to do it, take a look here in the docs

Hope that help you!😉

huangapple
  • 本文由 发表于 2023年3月7日 15:59:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定