2017-03-27 65 views
1

我嘗試做以下查詢模型Laravel:查詢在Laravel不查詢正確的結果

$num_stamps = Groupsheetstamp::where('status', '=', 'active') 
            ->where('user_id', '=', $user->id) 
            ->whereGroup_sheet_id($sheet->id) 
            ->orWhere(function ($query) use ($sheet, $user) { 
             $query->where('original_group_sheet_id', $sheet->id); 
            }) 
            ->get(); 

然而,這仍然返回那個的inactivestatus所有groupstamps,它看起來完全通過user_id的where子句。

我在查詢模型中做了什麼錯誤,因爲它沒有查詢正確的結果嗎?

從查詢輸出的例子可能是以下,與user id = 7sheet id = 12

"id" => 23 
"group_sheet_id" => 12 
"groupsheet_id" => 12 
"group_id" => 3 
"original_group_sheet_id" => 12 
"user_id" => 1 
"comment" => "" 
"status" => "inactive" 
"start_time" => "2017-03-16 17:09:06" 
"end_time" => "2017-03-16 23:06:39" 
"stamp_duration" => 6 
"hours" => 0 
"minutes" => 0 
"themonth" => "03.17" 
"manual_time" => "" 
"created_at" => "2017-03-16 23:06:33" 
"updated_at" => "2017-03-16 22:09:06" 

回答

1

這取決於究竟是什麼導致你期待。如果您想按組或關係進行搜索,則應該使用閉包。只是一個例子:

$num_stamps = Groupsheetstamp::where('status', 'active') 
    ->where('user_id', $user->id) 
    ->where(function($q) use ($sheet, $user) { 
     $q->where('group_sheet_id', $sheet->id) 
      ->orWhere('original_group_sheet_id', $sheet->id); 
    }) 
    ->get(); 

https://laravel.com/docs/5.4/queries#parameter-grouping

0

試試這個

$num_stamps = Groupsheetstamp::where('status', '=', 'active') 
           ->where('user_id', '=', $user->id) 
           ->where('group_sheet_id',$sheet->id) 
           ->orWhere(function ($query) use ($sheet, $user) { 
            $query->where('original_group_sheet_id', $sheet->id); 
           }) 
           ->get();