I’m trying to build a filter on my data using laravel ..
I have many to many relationships between the BasicItem model And AttValue Model and table Item_value between them.
this code works as what I want but I need it to be more dynamic depending on the user choice
ex. this $value is what the user choices
$values = array(
"0" => ['Dell','hp'],
"1" => ['Mac' ,'linux','windows'],
"2" => ['12.3' ,'12.5'],
"3" => ['8 GB RAM'],
);
$x = BasicItem::whereHas('AttValue', function($query) use ($values) {
$query->whereIn('attributeValue', $values["0"] );
})
->WhereHas('AttValue', function($query) use ($values) {
$query->whereIn('attributeValue',$values["1"]);
})
->WhereHas('AttValue', function($query) use ($values) {
$query->whereIn('attributeValue',$values["2"]);
})
->WhereHas('AttValue', function($query) use ($values) {
$query->whereIn('attributeValue',$values["3"]);
})
->get();
Now I want to Repeat the
->WhereHas('AttValue', function($query) use ($values) {
$query->whereIn('attributeValue',$values["$i"]);
statement as many as the length of the array
3
Answers
Simple and sweet query:
infinite/dynamic whereHas,
you can do this just whereHas. You can look your array put 1 array and you can whereIn this array.
If you want the query to work contextually the same, the best way is to do this:
Only results will show that have
attributeValue
in first array AND second array AND third array AND forth array and so on.EDIT: Changed solution to loop over whereHas in stead of whereIn