dimanche 29 novembre 2020

Get Data through relation in laravel

I'm using this query to get data using relation

 return Product::with('attributes')
        ->whereHas('attributes', function ($query) use ($attribute_id,$attribute_value){
            $query->whereIn('attribute_id', $attribute_id);
            $query->whereIn('value', $attribute_value);
        })
        ->paginate(10);

$attribute_id and $attribute_value are arrays, i'm getting data using this relation but when $attribute_id and $attribute_value are empty then i'm not getting any result but it should return result through product table if there are no attributes.

I have changed it to something like this:

 if(!empty($attribute_id))
                {
                    $query->whereIn('attribute_id', $attribute_id);
                }
                if(!empty($attribute_value))
                {
                    $query->whereIn('value', $attribute_value);
                }

model relation :

 public function attributes()
    {
        return $this->hasMany(ProductsAttribute::class, 'product_id ');
    }

Table:

id | Title     | Price

1    Title 1     5000
2    Product 2   7000

this is related to product_attribute table

id | product_id | attribute_id | attribute_name | value
 1     1              5             Color         Red
 2     1              6             Size           XL
 3     2              5             Color         Green

Is there any other way to make a check in query so that if attributes are not provided then atleast product data should return.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire