Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to UNION the statements using loop in Laravel

I am working on an app where I have a table called reps who has many dealers from dealers table and then again a dealer has many subdealers from subdealers table - I have foreign key named dealer_id from which I can find subdealers but the problem is I have dealers in an array which may increase or decrease depending on the rep which they belongs to

This is what I am trying to achieve but going nowhere

    foreach ($dealers as $dealer) {
        $subdealers = DB::table('subdealers')->where('dealer_id', '=', $dealer->id);
    }

Then iterate the $subdealers to get the value

But I know it's not possible as I am doing what I want is to UNION all results into one array and then iterate them in blade

How is this possible?

like image 995
Muhammad Avatar asked Oct 25 '25 02:10

Muhammad


1 Answers

Though it is too late, but it may help anyone else.
Here is what I did in same situation.

$i = 0;
foreach ($dealers as $dealer) {
    $q = DB::table('subdealers')->where('dealer_id', '=', $dealer->id);
    if($i < 1){
        $subdealers = $q;
    }else{
        $subdealers->union($q);
    }
    $i++
}
$subdealers = $subdealers->get();
like image 107
Tahir Shahzad Avatar answered Oct 27 '25 16:10

Tahir Shahzad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!