laravel - 在 laravel eloquent 中获得多个结果而不是一个
问题描述
我有一个简单的代码:Exam::find(1)->with('questions')->get()
. 我与考试和问题有多对多的关系。我期待一场考试id=1
和所有相关的问题,但我正在使用这段代码进行所有考试。这里有什么问题?
更新:我已经添加了修补程序输出,我希望它会有所帮助。
这是修补程序的输出:
>>> App\Exam::find(1)->with('questions')->get()
=> Illuminate\Database\Eloquent\Collection {#4263
all: [
App\Exam {#4212
id: 1,
title: "Exam 1",
duration: 20,
created_at: "2020-10-08 07:09:09",
updated_at: "2020-10-08 07:09:09",
mcqs: Illuminate\Database\Eloquent\Collection {#151
all: [
App\Question {#4273
id: 1,
question: "First Question",
a: "option a",
b: "option b",
c: "option c",
d: "option d",
},
App\Question {#4274
id: 2,
question: "Second Question",
a: "option a",
b: "option b",
c: "option c",
d: "option d",
},
App\Question {#4275
id: 3,
question: "Third Question",
a: "option a",
b: "option b",
c: "option c",
d: "option d",
},
],
},
},
App\Question {#4255
id: 2,
title: "Exam 2",
duration: 12,
created_at: "2020-10-08 07:09:24",
updated_at: "2020-10-08 07:09:24",
mcqs: Illuminate\Database\Eloquent\Collection {#4264
all: [
App\Question {#4276
id: 4,
question: "First Question",
a: "option a",
b: "option b",
c: "option c",
d: "option d",
},
App\Question {#4277
id: 5,
question: "Second Question",
a: "option a",
b: "option b",
c: "option c",
d: "option d",
},
],
},
},
],
}
解决方案
这应该有效:
$exam = Exam::with('questions')->where('id', 1)->first();
$questions = $exam->questions;
该->get()
方法总是返回一个集合。如果你只需要抓取一条记录->first()
就可以了。
这段代码也可以工作:
$exam = Exam::with('questions')->find(1);
->find(1)
只是一个别名->where('id', 1)->first()
--- 编辑
该with
方法不适用于您的陈述:
$exams = App\Exam::find(1)->with('questions')->get()
请记住,find(1)
是->where('id', 1)->first()
. 此时,您正在调用Exam
模型上的函数。为了使with
工作正常:
$exams = App\Exam::with('questions')->find(1)->get()
此外,如果您->get()
在最后使用,Laravel 会将您的对象模型转换为包含一个项目的集合。如果您只想要一项,此时您可以忽略它。
$exam = App\Exam::with('questions')->find(1);
从数据库中检索问题后加载问题的一种方法是使用该load
函数。
// grab one record from database
$exam = App\Exam::find(1);
// load questions
$exam->load('questions');
// assign to variable a collections of questions
$questions = $exam->questions;
如果关系配置正确,Laravel 会自动加载问题。以下代码也将起作用:
$exam = App\Exam::find(1);
dd($exam->questions);
我不知道为什么,但我更喜欢使用这个 sintax:
$exam = App\Exam::with('questions')->where('id', 1)->first();
也许是因为它更接近 SQL。
推荐阅读
- jooq - JOOQ自动生成的类中字段的SQLDataType有什么用
- css - 影响所有移动设备的 CSS 媒体查询
- css - 对于 CSS flexbox,允许元素缩小到最小(其固有宽度,绝对长度)
- python - 如何在一个代码中生成 2 个不同的图?
- node.js - $sort 在聚合管道 mongo 中不起作用
- flutter - 如何使用 Flutter 中良好渲染的字体进行黄金测试?
- java - 将集合映射与非主键列关联
- hpc - 在没有提交文件的情况下,如何在 condor 中提交请求特定 GPU 的作业?
- azure - Azure 资源锁定通过策略但通过 DevOps 删除
- r - 在 R 中绘制散点图