简体   繁体   中英

Laravel relationships belongsToMany

I want to fetch all orders and connect them with their statuses, but I want only the last status for each. I was trying to do it like this, but I only get the status for the first order the rest doesn't have any. How can I fix it?

static function actualKioskOrders()
{
    $orders = Order::query();

    return $orders->with([
        'statuses' => function ($query) {
            $query->orderBy('created_at', 'desc')->first();
        }
    ]);
}

In order model add this method, I suggest doing query on model class.

public function status(){
return $this-> belongsToMany(Status::class);
}

public function latestStatus() 

   return $this->status()->latest()->first();
}

.

I believe the easier way to do it would be

$orders = Order::with('status')->orderBy('created_at', 'desc');

Then if you dd($orders); you will have all the orders with their corresponded status.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM