首页 > 解决方案 > 按运送到国家/地区搜索产品

问题描述

我有一个表countries,其中包含以下字段:

title: string

我有一个表products,其中包含以下字段:

title,
description
...
ship_to: longText

的格式ship_to是这样的,例如一个产品可以用, ,IDs运送10到三个国家2030

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);
}

标签: phpsqllaravel

解决方案


我认为解决它的最好方法是产品和国家之间的多对多关系。为了获得它,请在数据库上创建一个新表,如下所示:

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');
}

推荐阅读