【问题标题】:Query multiple options attributes查询多个选项属性
【发布时间】:2017-07-09 17:45:36
【问题描述】:

我已经创建了一个搜索表单,但是我需要一些帮助来查询数据和结果:

基本上,我有一个产品列表,每个产品都有一个product_type,而且每个产品可以有很多材料属性。

我已经查询了产品的类型,这很容易,因为product type id 在同一个表(产品)中,但我必须使用用户选择的材料(属性)过滤产品.

我的控制器:

public function searchResults(Request $request)
    {

    if($request->has('type')){
        $type =  $request->type;
    }
    if($request->has('material')){
        $material = $request->material;
    }

    $query = \DB::table('products');

    //only one type             
   if ($request->has('type') && $type) {
        $query->where('product_type_id', $type);
    }

    // multiple values
    if ($request->has('material') && $material) {
//create query to get all the products with the materials selected
// the materials request comes in a array of ids ([1,2,3])..
    }

    $products = $query->get();

    return view('catalogs.index',compact('products'));

    }
}

产品型号:

class Product extends Model
{

    public function photos()
    {
        return $this->hasMany(ProductImage::class, 'product_id','id');
    }

    public function businessAreaName()
    {
        return $this->hasOne(ProductBusinessarea::class,'id','product_businessarea_id');
    }

    public function typeName()
    {
        return $this->hasOne(ProductType::class,'id','product_type_id');
    }

    public function businessAttributes()
    {
        return $this->hasMany(ProductAttributeBusinessarea::class);
    }

    public function materialAttributes()
    {
        return $this->hasMany(ProductAttributeMaterial::class);
    }

    public function areas(){
        return $this->belongsToMany(ProductAttributeBusinessarea::class);
    }
    public function materials(){
        return $this->belongsToMany(ProductAttributeMaterial::class);
    }
}

数据库:

产品

  • 身份证
  • 姓名
  • type_id

product_attribute_materials

  • product_id
  • product_material_id

产品材料

  • 身份证
  • 姓名

如何结合查询来获得所有产品和所选材料?

【问题讨论】:

  • 你能添加你的 Eloquent 模型及其关系吗?
  • 是的,我相信我可以,但我将如何进行这种组合?我需要传递材料参数,在产品模型中我该怎么做?
  • @OuailB 的意思是你可以显示你的 Eloquent 模型代码并将其添加到问题中!!
  • 对不起,我现在才添加。

标签: laravel laravel-5 eloquent laravel-5.3


【解决方案1】:

您可以加入表格,

$query = DB::table('products')
->join("product_attribute_materials","products.id","=","product_attribute_materials.product_id")
->whereIn("product_attribute_materials.product_material_id", $material)
->get();

U 可以从“product_attribute_materials”(表)中获取第一个产品 ID,然后从产品表中获取产品。 喜欢,

$material = DB :: table("product_attribute_materials")
->pluck('product_id')
->whereIn("product_material_id", $material)->toArray();

$query->whereIn('id', $material);

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多