2014-05-20 68 views
1

我是laravel的新手,對某些查詢方法感到困惑。laravel數據庫查詢請問`where`總是需要`first()`?

find($id)是有用的,並返回一個很好的數組,但有時我需要選擇其他字段而不是id

Laravel文檔說我可以使用where('field', '=', 'value')並返回一堆數據,這很好。

我不明白爲什麼我需要每次添加->first(),即使我非常肯定只有一行匹配查詢。

回答

0

即使我很確定只有一個單行匹配查詢。

好吧,Laravel無法讀懂你的想法 - 所以你需要告訴它你想做什麼。

你可以做任何

User::where('field', '=', 'value')->get() 

將返回匹配搜索的所有對象。有時它可能是一個,但有時它可能是2或3 ...

如果確定只有一個(或者你只是想第一),你可以做

User::where('field', '=', 'value')->first() 
6

它是這樣的:

$query->where(..)->orderBy(..)->limit(..) etc. 
// you can chain the methods as you like, and finally you need one of: 

->get($columns); // returns Eloquent Collection of Models or array of stdObjects 
->first($columns); // returns single row (Eloquent Model or stdClass) 
->find($id); // returns single row (Eloquent Model or stdClass) 
->find($ids); // returns Eloquent Collection 
// those are examples, there are many more like firstOrFail, findMany etc, check the api 

$columns is an array of fields to retrieve, default array('*') 
$id is a single primary key value 
$ids is an array of PKs, this works in find method only for Eloquent Builder 

// or aggregate functions: 
->count() 
->avg() 
->aggregate() 
// just examples here too 

所以方法取決於你想要什麼檢索(數組/集合或單個對象)

此外,返回對象還取決於您正在使用的構建器(Eloquent Builder或Query Builder):

User::get(); // Eloquent Colleciton 
DB::table('users')->get(); // array of stdObjects 
0
  • get()返回對象的數組(多行)

  • 第一()返回一個單個對象(行)

當你知道它只返回一行時,你當然可以使用get(),但在處理結果時需要記住這一點:

使用get()

$rez = \DB::table('table')->where('sec_id','=','5')->get(); 
//will return one row in an array with one item, but will be addressed as: 
$myfieldvalue = $rez[0]->fieldname; 

使用第一()

$rez = \DB::table('table')->where('sec_id','=','5')->first(); 
// will also return one row but without the array, so 
$myfieldvalue = $rez->fieldname; 

所以這取決於你想如何訪問的結果查詢:作爲一個對象或數組,a nd還取決於「你知道」查詢將返回的內容。

  • first()與SELECT語句結尾處的LIMIT 1相當。即使你的查詢會返回多行,如果你使用first()它只會返回第一行