jeudi 13 octobre 2016

Laravel Eloquent collections Union not as expected

As everyone new to Laravel says, "HELP!" My problem is that the union method of the Collection class is not returning the results I am expecting. I am basically merging two collections like a full outer join using a particular key (not the id).

$needsOrdering = Parts::where("isactive", 1)
        ->where("forordering", 1)
        ->select(\DB::raw("concat('p',id) as idx, suppliers.suppliercode as suppcode, sku as partsku, descr as descriptn, reorderqty"))
        ->join("suppliers", "suppliers.supplierid", "=", "part.supplierid")
        ->whereNotIn("sku", function($q){
            $q->select("sku")->from("order")
                ->where("isactive", 1)
                ->whereIn("orderstatus", [3, 2])
                ->get();
        })->get();

and

$allPossibleOrders = Order::where("isactive", 1)
        ->select(\DB::raw("concat('o',id) as idx, suppliers.suppliercode as suppcode, sku as partsku, qty1, qty2, qty3, totalqty"))
        ->whereIn("ordertype", [1, 2, 3, 4])
        ->whereNotIn("orderstatus", [4, 0])
        ->whereIn("opstatus", [2, 5])
        ->join("suppliers", "suppliers.supplierid", "=", "orders.supplierid")
        ->get();

I have the table structure as follows:

Table Part:
1. id
2. sku
3. descr
4. reorderqty
5. supplierid
...etc.

Table Order
1. id
2. supplierid
3. sku
4. qty1
5. qty2
6. qty3
...etc.

Table Suppliers
1. supplierid
2. suppliercode
... etc.

Suppose I have in my dd($needsOrdering) items like:
1. Mouse
2. Keyboard
3. iphone

and in my dd($allPossibleOrders) items like:
1. Barack-O-1
2. Barack-O-2
3. G-Shock
4. Charger
5. iphone
6. Tumblr
7. Mouse

the dd($result) result of
$result = $needsOrd->union($allPossibleOrders)
is:
1. Mouse
2. Keyboard
3. iphone
4. Charger
5. iphone
6. Tumblr
7. Mouse

I was expecting a result such as:
1. Mouse
2. Keyboard
3. iphone
4. Barack-O-1
5. Barack-O-2
6. G-shock
7. Charger
8. Tumblr

How do I do this? Is this possible? Thanks for the help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire