when to use get() in query laravel 5

2019-08-06 11:34发布

I have a basic query set up in the show method of a laravel resource

public function show($id){
     $results = Student::find($id);

     $drives= Drive:: where('student_id', $id);
}

The query for $results works perfectly. The query for $drives does not work unless I do ->get() at the end of it. Why is this? what's the difference between the two queries so that one requires the ->get() and the other does not? Solving this problem took me like 5 hrs and i'm just curious as to the functionality behind it so i can avoid this headache in the future.

3条回答
Explosion°爆炸
2楼-- · 2019-08-06 11:54

Using the function find() on a model gets a query result based on the primary key of the model, id in this case.

When using where(), it gets a collection (an object of all query results), so if you only want the first result you must call $drives=Drive::where('student_id', $id)->first();

Here is a more in-depth explanation: the difference of find and get in Eloquent

查看更多
叼着烟拽天下
3楼-- · 2019-08-06 12:01

use get to execute a builder query. unless you run the get() query wont be executed. get will return a collection.

1 - Use query builder to build queries however you want.

$drives= Drive:: where('student_id', $id);
dd($drives); // will return a query builder, you can use it to build query by chaining

2 - when you are ready to execute the query call get()

$drives= Drive:: where('student_id', $id);
$result = $drives->get() 
dd($result); // will return a database query result set as a collection object

If you want to get a single object by id use find, to get a single object

$results = Student::find($id);
dd($result); will return a single model
查看更多
贼婆χ
4楼-- · 2019-08-06 12:15

Some eloquent expressions have a get implicitly. Those ones who are made by a Query Builder will need a ->get() call, find(), findOne()... won't need a get().

https://laravel.com/docs/5.6/eloquent#retrieving-models

https://laravel.com/docs/5.6/queries

查看更多
登录 后发表回答