php - 按运送到国家/地区搜索产品
问题描述
我有一个表countries
,其中包含以下字段:
title: string
我有一个表products
,其中包含以下字段:
title,
description
...
ship_to: longText
的格式ship_to
是这样的,例如一个产品可以用, ,IDs
运送10
到三个国家20
30
ship_to: {[10,20,30]}
现在,我想做的是按可以运送到的国家/地区过滤产品。因此,例如,我给出了一个包含 10,20(国家 ID)的数组,并且我想找到至少运送到这些国家之一的产品。
但是我想不出任何有效的方法。我在考虑 foreach 循环orWhereIn('ship_to', $givenArrayOfCountryIds)
或类似的东西,但我发现随着时间的推移它会成为这个过滤器查询的瓶颈。
如何修复我的数据库设计,或者可能有一个隐藏的 Laravel 雄辩功能?我找不到任何可以完成这项任务的东西。
这是我在意识到这行不通之前写的一些代码:
<?php
namespace App\Model\Filters\Product;
use App\Model\Contracts\AbstractClasses\Filter;
class ShipsTo extends Filter
{
protected function applyFilter($builder)
{
$filterName = $this->filterName();
$shipsTo = request()->$filterName;
if ($shipsTo && count($shipsTo) > 0) {
return $builder->whereHas('countries', function ($query) use ($shipsTo) {
$query->whereIn('id', $shipsTo);
});
}
return $builder;
}
}
我使用管道将多个过滤器合二为一。这是调用管道的代码:
public function search($term, $limit)
{
$builder = Product::select([
'id',
'title',
'image',
'price',
'sale_price'
])->active();
$builder = app(Pipeline::class)
->send($builder)
->through([
ShipsTo::class,
])
->thenReturn();
return $builder->paginate($limit);
}
解决方案
我认为解决它的最好方法是产品和国家之间的多对多关系。为了获得它,请在数据库上创建一个新表,如下所示:
CREATE TABLE products_countries(
product_id int not null, /* or the domain of product table primary key */
country_id int not null, /* or the domain of country table primary key */
primary key(product_id, country_id),
FOREIGN KEY (product_id) REFERENCES Product(id), //or the product table primary key
FOREIGN KEY (country_id) REFERENCES Country(id), //or the product country primary key
)
而不是产品型号:
public function countries(){
return $this->belongsToMany('App\Country');
}
而不是在国家模型上:
public function products(){
return $this->belongsToMany('App\Product');
}
推荐阅读
- spring-boot - bean 类 [java.util.ArrayList] 的无效属性“books [0]”
- excel - 尝试使用过滤器从访问中导出查询的数据,但是当它在 excel 中打开时,数据没有被过滤
- android - 如何在 Spinners 中分离标签和值?
- html - Angular中的FormGroup异步问题Edge vs Chrome
- mysql - 我需要 Mysql 查询来查找所选月份和年份的可用日期,不包括从表中获取的日期
- date - 截断 Hive 中的日期值
- azure - Jenkins azure 部署错误:az login 错误问题
- r - 我如何仅按名称映射我们的州?在 R 中
- spring - Spring web 这是 MVC 吗?
- c - 从二进制文件中读取和显示时间戳