我目前正尝试在我的数据库中实现关键字的搜索。因此,我拆分了一个由逗号分隔的字符串,因此我得到了一个包含可变数量的元素(一个关键字)的数组。
我知道我可以使用这样一个雄辩的结构:
$products = Product::where([['keywords', 'LIKE', %samsung%], [keywords, 'LIKE', 's7']])->paginate(15); 要查找具有关键字samsung,galaxy,s7的产品,请执行以下操作。
现在我需要这个东西,但它是为可变数量的搜索查询部分自动生成的,所以对于数组中的每个关键字,我需要添加一个‘关键字’,‘喜欢’,'...'...
我如何使用做到这一点?
发布于 2017-02-05 23:15:25
使用闭包。首先,确保将关键字列表存储到数组或类似的文件中。然后..。
$keywords = ['samsung', 's7', 'what else'];
$products = Product::where(function ($query) use ($keywords) {
foreach ($keywords as $keyword) {
$query->orWhere('keyword', 'like', $keyword);
}
})->paginate(15);其他示例
$keywords = [
['name', 'LIKE', $searchQuery],
['category_id', '=', $selectedSubcategory],
];
$products = Product::where(function ($query) use ($keywords) {
foreach ($keywords as $keyword) {
$query->where($keyword);
}
})->paginate(15);除其他外
$keywords = [
['name', 'LIKE', $searchQuery],
['category_id', '=', $selectedSubcategory],
['please_id', '=', $learnPhpArray],
];
$products = Product::query();
foreach ($keywords as $keyword) {
$products = $products->where($keyword);
}
return $products->paginate(15);orWhere是做什么的?它是否使用AND连接查询部分?
不,和OR在一起。作为逆(?)默认情况下,where本身会执行AND。
参考文献
发布于 2017-02-05 23:17:54
它不就是为了生成数组吗?还是我误解了这个问题?
<?php
$keys = ['samsung', 'lg', 'sony', 'nokia', 'apple'];
$keywords = [];
foreach($keys as $key){
$keywords[] = ['keywords', 'LIKE', '%'.$key.'%'];
}
$products = Product::where($keywords)->paginate(15);发布于 2017-02-05 23:18:18
您可以这样做:
$query = "Samsung galaxy S7"; // Or whatever the query is
$words = preg_split("/[ ,.]/",$query); //Split on space comma or dot. Maybe need more?
$queries = array_map(function ($word) {
return [ "keywords", "LIKE", "%$word%" ];
}, $words); //Transform single words to array of queries
$products = Product::where($queries)->paginate(15); 查看代码的第一部分是如何工作的:https://eval.in/730772
https://stackoverflow.com/questions/42053525
复制相似问题