diff --git a/app/index/controller/Product.php b/app/index/controller/Product.php index 080502bd..f18ad2d8 100644 --- a/app/index/controller/Product.php +++ b/app/index/controller/Product.php @@ -154,6 +154,39 @@ class Product extends Common return View::fetch('category'); } + /** + * 产品搜索 + */ + public function search() + { + $keywords = request()->param('keywords', ''); + + // 关键词搜索 + $products = ProductModel::field([ + 'id', + 'name', + 'short_name', + 'cover_image', + 'spu' + ]) + ->where(fn ($query) => $query->withSearch(['keywords'], ['keywords' => $keywords])) + ->language($this->lang_id) + ->enabled(true) + ->onSale(true) + ->onShelves(true) + ->order(['sort' => 'asc', 'id' => 'desc']) + ->select() + ->each(function ($item) use($keywords) { + $item['spu'] = str_replace($keywords, ''.$keywords.'', $item['spu']); + $item['name'] = str_replace($keywords, ''.$keywords.'', $item['name']); + $item['short_name'] = str_replace($keywords, ''.$keywords.'', $item['short_name']); + return $item; + }); + View::assign('products', $products); + + return View::fetch('search'); + } + /** * 产品详情页 */ diff --git a/app/index/model/ProductModel.php b/app/index/model/ProductModel.php index e5d18164..5b8a74f3 100644 --- a/app/index/model/ProductModel.php +++ b/app/index/model/ProductModel.php @@ -4,6 +4,7 @@ declare (strict_types = 1); namespace app\index\model; use app\common\model\ProductBaseModel; +use think\facade\Db; use think\model\concern\SoftDelete; /** @@ -74,4 +75,10 @@ class ProductModel extends ProductBaseModel { $query->where('is_new', '=', (int)$stat); } + + // 关键词搜索 + public function searchKeywordsAttr($query, string $keywords) + { + $query->whereRaw('BINARY spu LIKE "%' . $keywords . '%" OR BINARY name LIKE "%' . $keywords . '%" OR BINARY short_name LIKE "%' . $keywords . '%"'); + } } diff --git a/app/index/view/product/search.html b/app/index/view/product/search.html index 0d52260e..2356987d 100644 --- a/app/index/view/product/search.html +++ b/app/index/view/product/search.html @@ -5,27 +5,33 @@ {block name="main"} {/block} \ No newline at end of file