Support the ongoing development of Laravel.io →
posted 7 years ago

I am trying to migrate from cakephp to laravel but came across a huge challenge in the process in my application, users hasMany schools, schools belongsTo user. This is my user table table:users: id name membership

table: schools: id name

I want to write a query that fetches school record and firstly sort it by user.membership then when it comes to schools whose users belong to the same membership, sort it by the school.name //my user model: public function schools() { return $this->hasMany('App\School', 'user_id'); }

//my school model public function user() { return $this->belongsTo('App\User'); }

//my schoolsController public function viewschools() {

   $schools = Schools::select('id', name')
   ->with(['user' => function ($query) {
    $query->orderBy('membership', 'asc');
    }])
    ->orderBy('name')
    ->paginate(70);

    return view('schools.viewschools', array('schools' => $schools, 'title' => 'News Display'));


} 

the result sorts by school alone but ingnore the user.membership sort command

i can achieve the same thing with cakephp 2.X with just this:

$this->Paginator->settings = array( 'order' => array('User.membership' => 'asc','School.name'=>'asc'), 'limit' => 50, ); $schools = $this->Paginator->paginate('School');

Last updated 2 years ago.
0

You don't want to use with for your use case. with is being used to solve the N+1 query issue; where you can eager load your data. with does NOT make a join that you can multi-sort on.

What you want, is a join operator so you can orderBy multiple attributes from that result.

Last updated 7 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Yomi Ojo Yomi Ojo yormie Joined 24 Jun 2017

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.