Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

396
Views
Laravel: order by relationship (product sorted by first order date)

I have products and orders. For a product I can get the orders and also get the first order (using recently added ofMany):

public function orders() {
    return $this->hasMany(Order::class)
}

public function firstOrder() {
    return $this->hasOne(Order::class)
        ->ofMany('created_at', 'min');
}

I can get products with recent first orders, but I'm not sure how to order the products by that date:

Product::whereHas('firstOrder', fn($q) => $q->where('created_at', '>=', now()->subDays(7)))
    ->with('firstOrder')
    // ->orderBy('firstOrder.created_at') 
    // orderBy fails: The multi-part identifier "firstOrder.created_at" could not be bound.

How can I get the products ordered by first order date that have a recent (e.g. last week) first order as part of the database query (so: no ->get()->sortBy(...))?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

What you're trying to do is not easy out of the box.

One way is to use a subquery join (you can move the date condition to the subquery)

$firstOrders = DB::table('orders')
    ->select('product_id', DB::raw('MIN(created_at) as first_order_created_at'))
    ->where('created_at', '>=', now()->subDays(7))
    ->groupBy('product_id');

$products = Product::with('firstOrder')
    ->joinSub($firstOrders, 'first_orders', function ($join) {
            $join->on('products.id', '=', 'first_orders.product_id');
        })
    ->orderBy('first_orders.first_order_created_at', 'ASC')
    ->get();

Hope it gives you at least a lead to what you're trying to do.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!