I have 2 table with many to many and pivot table ,
Sku and attribute_value
SKU table :
id | code |
---|---|
1 | sku1 |
2 | sku2 |
3 | sku3 |
Attribute value
id | name |
---|---|
1 | Red |
2 | Blue |
3 | Black |
4 | Pink |
5 | Big |
6 | Small |
Pivot Table :
id | sku_id | att_value |
---|---|---|
1 | 1 | 2 |
2 | 1 | 5 |
2 | 2 | 2 |
2 | 2 | 6 |
2 | 3 | 3 |
2 | 3 | 6 |
Now my problem is : how can i find the sku_id
when I have 2 att_value
(ex : 2 & 6 ) ( Blue and Small )
Sku::whereHas('Attributevalue', function ($query) {
$query->whereIn('sh_sku_attribute.attribute_id',[2,6] ) ;
})->first() ;
Saeed M is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
One way you could go about this is to define a model for the pivot table and declare belongsTo relationships to both tables i.e SKU and Attribute.
class PivotTable extends Pivot{
public function sku(): belongsTo
{
return $this->belongsTo(Sku::class);
}
public function attribute(): belongsTo
{
return $this->belongsTo(Attribute::class);
}
}
After this, you can access both table or models directly from each other through the pivot by creating a relationship to both models directly on each as shown below
SKU MODEL:
class SKU extends Model{
public function attributes(): hasManyThrough
{
return $this->hasManyThrough(
Attribute::class,
PivotTable::class,
'sku_id,
'id', 'id', 'attribute_id'
);
}
}
Attribute MODEL:
class Attribute extends Model{
public function sku(): hasManyThrough
{
return $this->hasManyThrough(
Sku::class,
PivotTable::class,
'attribute_id,
'id', 'id', 'sku_id'
);
}
}
Afterwhich, you can query the attributes model and get the sku id related to each as shown below
$sku = Attributes::with('sku')
->whereIn('id', [2,6])
->get()->pluck('sku.id')