Returning all where relationship doesn't exist

Posted 1 month ago by Fifiasco

Hi all I essentially have an Order model. In this particular project there can be cases where an order can belong to another order, using a "belongsToMany" relationship. Please see block below.

public function childOrders()
    {
        return $this->belongsToMany(Order::class , null, 'main_order_id', 'child_order_id');
    }

    public function parentOrders()
    {
        return $this->belongsToMany(Order::class , null, 'child_order_id', 'main_order_id');
    }

The orders also belong to a user, "belongsTo" on the order and "hasMany" from the user model.

Currently I am simply retrieving the users orders in a very bog standard way.

$orders = $user->orders;

However I only want the user to be able to view orders that do not have parentOrders. Using the block below is how i am currently achieving this..

foreach($orders as $order){
    if(!$order->parentOrders->count() > 0){
        //show me the order
    }
}

However there will be multiple places this can be viewed and i want to wrap it all inside a method in my user model something along the lines of

public function viewableOrders()
{
    //Only retrieve the orders based on the code block above.
}

I am guessing there is a really clean way to do this, probably using queries (something I have always struggled with). Currently My best guess is going some sort of hack job like so..

public function viewableOrders()
    {
        $orders = [];
        $all = $this->orders;
        foreach($all as $single)
        {
            if(!$single->parentOrders->count() > 0){
                array_push($orders, $single);
            }
        }

        return collect($orders);
    }

Which is really not ideal as I will still need access to multiple relationships available to the order.

If anyone could point me in the right direction I would be super happy and grateful.

Thank you!

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.