在Laravel中查询不会查询正确的结果

时间:2017-03-27 17:11:26

标签: php 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();

但是,这仍然会返回status inactive的所有groupstamp,并且它会完全查看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"

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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();