请一些人可以根据Laravel查询构建器的优化使用联接的帮助
Product::select(DB::raw('
products.*
,(select name from users where users.id=products.user_id) as user_name
'))
->where(function ($query) use ($searchKey) {
if (trim($searchKey) != '') {
$query->where('name', 'like', '%' . trim($searchKey) . '%');
}
})
->orderBy($orderBy,$orderType)
->paginate(10)
答案 0 :(得分:1)
也许是这样的:
//Start your query as usual, but just join the user data in. Do not use paginate function yet as this will trigger the query to execute.
$productQuery = Product
::selectRaw('products.*, users.name as user_name')
->join('users', 'users.id', 'products.user_id')
->orderBy($orderBy, $orderType);
//Check (for each param) if you want to add where clause
//You dont need to nest the where function, unless you have more filters, and need to group statements together
if(!empty(trim($searchKey))) {
$productQuery->where('name', 'like', '%' . trim($searchKey) . '%');
}
//Execute query
$products = $productQuery->paginate(10);
请注意,查询构建器仅使用诸如chunk
,get
,first
或paginate
(还有更多)之类的特定功能来接触数据库。建立查询时,您可以完全自由地添加过滤器/排序/分组,直到执行查询为止。
我希望它能对您有所帮助。