I don’t understand. How is this not a simple where on multiple columns?
Building query
Hi,
I've got this table :
id sku_id article_id article_attribut_valeur_id attribut_id
37 37 49 124 14
38 37 49 196 26
39 38 49 122 14
40 38 49 194 26
41 39 19 277 39
42 39 19 280 40
43 39 19 279 41
44 40 19 277 39
45 40 19 278 40
46 40 19 279 41
47 41 19 281 39
48 41 19 280 40
49 41 19 279 41
It represents the characteristic of each Sku of a Product (Article). Dynamic number of Attribut_id (dynamic number of rows) for a given Sku. It can be only one sku for a given Product(Article) having a particular set of attribut_id / article_attribut_valeur_id.
i'd like to know, for a given article_id (say 19), if a combination of attribut_id / article_attribut_valeur_id exist on a sku_id.
A bit of context, modifying a sku, if a user change 1 article_attribut_valeur_id for an attribut_id, I need to check if another Sku (of this same Article) has already this set of attribut_id / article_attribut_valeur_id.
Thx for your help !
@seb_run Just a quick note now before I’m off to bed, but just thought of this:
If you group your results by sku_id and then limit to groups having at least the same number of rows as the conditions you’re filtering by, I think that should give you the right result. Rows with different SKU IDs would end up in different groups, so they won’t falsely inflate the number.
So something like this:
SELECT sku_id FROM article_sku WHERE article_id = 19 AND (
(attribut_id = 1 AND article_attribut_valeur_id = 3) // $condition[1]
OR (attribut_id = 2 AND article_attribut_valeur_id = 4) // $condition[2]
) GROUP BY sku_id HAVING COUNT(*) >= $conditionCount
Or in Eloquent:
$existing = SKU:select('sku_id')
->where('article_id', $sku->article_id)
->where(function ($query) use ($attributes) {
foreach($attributes as $a) {
$query->orWhere(function ($query) use ($a) {
$query->where('attribut_id', $a['attribute'])->where('article_attribut_valeur_id', $a['value']);
});
}
})
->groupBy('sku_id')
->havingRaw('COUNT(*) >= ?', count($attributes))
->get()
;
if ($existing->count() > 0) {
// The combination exists
} else {
// The combination doesn’t exist
}
Please or to participate in this conversation.