php - 拉拉维尔 | 无法获得匹配子串的结果
问题描述
问题 :
我有一张桌子product
,上面有一堆列。其中之一是name
。问题是 :
示例条目:
- 名称:盐粉。
- 名称:辣椒粉R
问题
当我进行查询时, https://example.com/public/api/products?search=name%3Apowder
我得到 0 个结果。
期待是回归
盐粉和辣椒粉,因为“粉”一词在两者中都很常见。
现在,当我对 进行查询时https://example.com/public/api/products?search=name%3Asalt+powder
,我得到Salt powder
了结果。
这是我的controller
& 我一直试图在索引中实现的内容:
public function index(Request $request)
{
if (Query::has('search')) { ------>>> I know that something is terribly wrong here.
$queryString = Query::get('search');
$products = Products::where('name', 'LIKE', "%$queryString%")->orderBy('name')->paginate(5);
}
try{
$this->productRepository->pushCriteria(new RequestCriteria($request));
$this->productRepository->pushCriteria(new LimitOffsetCriteria($request));
$this->productRepository->pushCriteria(new ProductsOfFieldsCriteria($request));
if($request->get('trending',null) == 'week'){
$this->productRepository->pushCriteria(new TrendingWeekCriteria($request));
}
else{
$this->productRepository->pushCriteria(new NearCriteria($request));
}
$products = $this->productRepository->all();
} catch (RepositoryException $e) {
return $this->sendError($e->getMessage());
}
return $this->sendResponse($products->toArray(), 'Products retrieved successfully');
}
我的productRepository.php
:
<?php
namespace App\Repositories;
use App\Models\Product;
use InfyOm\Generator\Common\BaseRepository;
use Prettus\Repository\Contracts\CacheableInterface;
use Prettus\Repository\Traits\CacheableRepository;
class ProductRepository extends BaseRepository implements CacheableInterface
{
use CacheableRepository;
/**
* @var array
*/
protected $fieldSearchable = [
'name',
'seokeywords',
'price',
'discount_price',
'description',
'capacity',
'package_items_count',
'unit',
'itemsAvailable',
'featured',
'store_id',
'category_id',
'brand_id'
];
/**
* Configure the Model
**/
public function model()
{
return Product::class;
}
/**
* get my products
**/
public function myProducts()
{
return Product::join("user_stores", "user_stores.store_id", "=", "products.store_id")
->where('user_stores.user_id', auth()->id())->get();
}
}
有人可以帮助理解我应该修改什么或哪个语句吗?我已经尝试过更改,但大多数尝试都以错误告终。任何帮助深表感谢。我可以分享你们可能感兴趣的任何文件
解决方案
您可以使用$request->query
来获取查询字符串,并且由于其中包含“名称:”,因此您需要提取搜索词:
if ($queryString = $request->query('search')) {
[$column, $term] = explode(':', $queryString);
$products = Products::where('name', 'LIKE', "%{$term}%")
->orderBy('name')
->paginate(5);
}
注意:你不是缺少一个 else 子句吗?您似乎正在覆盖 $products 变量。
推荐阅读
- javascript - 如何使用滚动时加载的 Quasar 页面创建
- nestjs - 找不到模块“@nestjs/core”或其对应的类型声明
- domain-driven-design - 聚合间引用必须使用主键?
- javascript - 将切换开关更改为默认打开
- c# - TextBox 资源中的 C# UWP 数据绑定
- javascript - 如何从 Asp.Net Core MVC 应用程序中的控制器访问 javascript 代码
- neo4j - Neo4j 导入其中字段具有多个值
- android - 如何切换不在清单中的主要活动?
- github - 无法从 Grails 应用程序中的 Github Api 获取数据
- email - 如何仅使用 id 创建新记录