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
- 名
我怎樣才能結合查詢來獲取所有的產品與材料的選定?
你可以添加你的Eloquent模型及其關係嗎? – OuailB
是的,我相信我可以,但我怎麼做這個組合?我需要傳遞材料參數,我會在產品模型中做什麼? –
@OuailB意味着你可以展示你的雄辯模型代碼並將其添加到問題中! – Maraboc