Hi guys, i created a search form, but i need some help in how to query the data and results:
Basically i have a list of products, and in each product there is one product_type and also each product can have many materials attributes.
I already made the query to get the type of products, and that is easy since the product type id is in the same table (products) but than i have to filter the products with the materials (attributes) selected by the user.
My controller:
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'));
}
}
Product Model:
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);
}
}
DATABASE:
products:
- id;
- name;
- type_id;
product_attribute_materials:
- product_id;
- product_material_id
product_materials:
- id;
- name;
How i can combine the query to get all the products with the materials selected?