大家好,有人可以帮助我
我需要从文本输入中搜索表格中的用户
如果我们只是通过名字或姓氏搜索我就做了,但是如果我们在文本输入中写下姓名和姓氏就不能这样做
这是我们只写名字或姓氏时的代码:
$data = User::where('name', 'LIKE', '%'. $search .'%')
->orWhere('firstname', 'LIKE', '%'. $search .'%')
->get();
我认为它是这样的,但它不起作用:D
首先我确实拆分了输入中给出的文本,这里是代码
$words = explode(' ', $search);
$firstword = $words[0];
$lastword = $words[1];
$data = User::where('name', 'LIKE', '%'. $firstword .'%')
->where('firstname', 'LIKE', '%'. $lastword .'%')
->get();
答案 0 :(得分:3)
您可以执行以下操作来搜索名字和姓氏列的所有单词:
// Get the search terms and define the columns we're looking at
$terms = explode(' ', $search);
$columns = ['firstname', 'lastname'];
// Start with an initial null query. I'm pretty sure Laravel expects a where before an orWhere, so this is an alright way to make that check.
$query = null;
// For each of the search terms
foreach ($terms as $term) {
// For each column
foreach ($columns as $column) {
// If we have not yet started a query, start one now by applying a where to the User model. If we have started a query i.e. $query is not null, then use an orWhere
if (is_null($query)) {
$query = User::where($column, 'LIKE', '%' . $term . '%');
} else {
$query->orWhere($column, 'LIKE', '%' . $term . '%');
}
}
}
// Finally, get the results
$results = $query->get();
答案 1 :(得分:1)
你的问题是这个(或者在哪里代替):
'end => start'
答案 2 :(得分:0)
),您可以执行以下操作
$posts = Post::where('COLUMN_ONE','SEARCH STRING')->orWhere('COLUMN_TWO','LIKE','%'.$search)->paginate(2);
希望这会有所帮助