我遇到了一个问题,user_id似乎被Laravel雄辩的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);发布于 2018-11-13 17:37:43
这是正确的行为,因为在where之后添加了一个orWhere子句。
这将导致这样的查询:
SELECT * FROM your_table WHERE (user_id = xxx) OR (some condition that results true)因为false OR true等于true,所以忽略了第一个子句(因为第二个子句是true)。
https://stackoverflow.com/questions/53266870
复制相似问题