我遇到一个问题,其中user_id
似乎被Laravels雄辩的ORM完全忽略了。
鸽子桌子
id user_id name father_id mother_id ringnumber
gender color created_at updated_at landcode
(这些是我的专栏(如果有人知道如何更好地格式化),请告诉我)
我有一个搜索,将从中将搜索参数q
路由到该函数所在的我的SearchController.php:
namespace App\Http\Controllers;
use App\Pigeon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
class SearchController extends Controller
{
public function index()
{
$q = Input::get('query');
$userId = Auth::user()->id;
$pigeons = Pigeon::where([
['user_id', '=', $userId],
['name','LIKE','%'.$q.'%']
])
->orWhere('ringnumber','LIKE','%'.$q.'%')
->sortable()
->paginate(15);
dd($pigeons);
return view('backend.pigeon.pigeonlist')->with('pigeons', $pigeons);
}
}
由于某种原因,这个雄辩的查询生成器似乎完全忽略了'user_id', '=', $userId
,这是重要的部分,因为我只想为当前登录用户搜索鸽子。
下面是这种查询的结果,问题是存在着各种user_id
的鸽子,而不仅仅是搜索它们的一个用户。
LengthAwarePaginator {#259 ▼
#total: 150
#lastPage: 10
#items: Collection {#267 ▼
#items: array:15 [▼
0 => Pigeon {#268 ▶}
1 => Pigeon {#269 ▶}
2 => Pigeon {#270 ▶}
3 => Pigeon {#271 ▶}
4 => Pigeon {#272 ▶}
5 => Pigeon {#273 ▶}
6 => Pigeon {#274 ▶}
7 => Pigeon {#275 ▶}
8 => Pigeon {#276 ▶}
9 => Pigeon {#277 ▶}
10 => Pigeon {#278 ▶}
11 => Pigeon {#279 ▶}
12 => Pigeon {#280 ▶}
13 => Pigeon {#281 ▶}
14 => Pigeon {#282 ▶}
]
}
#perPage: 15
#currentPage: 1
#path: "http://mywebsite.test/pigeon/search"
#query: []
#fragment: null
#pageName: "page"
+onEachSide: 3
}
请注意,我从这里获得了一些信息:How to create multiple where clause query using Laravel Eloquent?
问题已解决: 首先,我有一个orWhere否决了where,所以这对我来说很愚蠢。 其次,我真正的问题是我试图只获取通过以下代码工作的当前登录用户的记录:
$pigeons = Pigeon::where('user_id', \Auth::id())
->where(function($query) use ($q) {
$query->where('name', 'LIKE', '%'. $q .'%');
})
->sortable()
->paginate(15);
答案 0 :(得分:1)
这是正确的行为,因为要在where之后添加orWhere
子句。
这将导致如下查询:
SELECT * FROM your_table WHERE (user_id = xxx) OR (some condition that results true)
由于false OR true
等于true
,因此第一个子句被忽略(因为第二个子句为true)