我在laravel资源的show方法中设置了基本查询
public function show($id){
$results = Student::find($id);
$drives= Drive:: where('student_id', $id);
}
$ results的查询效果很好。 $驱动器的查询不起作用,除非我这样做 - > get()在它的末尾。为什么是这样?这两个查询之间的区别是什么,以便一个需要 - > get()而另一个不需要?解决这个问题花了我5个小时,我只是对其背后的功能感到好奇,所以我可以避免将来的这种头痛。
答案 0 :(得分:2)
某些eloquent
表达式隐含get
。那些由Query Builder
制作的人需要->get()
来电,find(), findOne()...
不需要get()
。
答案 1 :(得分:0)
使用get执行构建器查询。除非你运行get()查询不会被执行。 get将返回一个集合。
1 - 使用查询构建器构建您想要的查询。
$drives= Drive:: where('student_id', $id);
dd($drives); // will return a query builder, you can use it to build query by chaining
2 - 准备好执行查询时调用get()
$drives= Drive:: where('student_id', $id);
$result = $drives->get()
dd($result); // will return a database query result set as a collection object
如果您想通过id获取单个对象,请使用find,以获取单个对象
$results = Student::find($id);
dd($result); will return a single model
答案 2 :(得分:0)
在模型上使用函数find()
获取基于模型主键的查询结果,在这种情况下为id
。
使用where()
时,会获得一个集合(所有查询结果的对象),因此如果您只想要第一个结果,则必须调用$drives=Drive::where('student_id', $id)->first();