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