2017-07-07 72 views
0

我已经创建了一个搜索表单,但我需要在如何查询数据和结果的一些帮助:查询多个选项属性

基本上,我有一个产品列表,并在每个产品有一个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); 
    } 
} 

数据库:

产品

  • ID
  • TYPE_ID

product_attribute_materials

  • PRODUCT_ID
  • product_material_id

product_materials

  • ID

我怎样才能结合查询来获取所有的产品与材料的选定?

+1

你可以添加你的Eloquent模型及其关系吗? – OuailB

+0

是的,我相信我可以,但我怎么做这个组合?我需要传递材料参数,我会在产品模型中做什么? –

+1

@OuailB意味着你可以展示你的雄辩模型代码并将其添加到问题中! – Maraboc

回答

0

您可以加入表,

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

OR

U可以从 “product_attribute_materials”(表)获得的第一个产品的ID,然后把产品从产品表。 like,

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

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

我希望它有帮助。