user3386779
user3386779

Reputation: 7175

make the display order based on another table value

I have two tables request and status_tracker. I want to list the row in top which has only one entry in status tracker.

I have the query in $user=DB::table('request')->select('request.*)->get();

I want to add the order based on status_tracker table. If request_id has count '2' in status_tracker table I want to display in top of the table

 $user=DB::table('request')->select('request.*)(order may happened here)->get();

if ID 19,11,15 has 2 count in status_tracker it should display first and rest of them will display below as 19,11,15,18,17,16,14,13,12,10.

Is it possible by order the row based on another table field count in laravel?

Upvotes: 2

Views: 60

Answers (1)

Pol Lluis
Pol Lluis

Reputation: 1162

You could use 'withCount' which will add a column named {relation}_count and orderBy with that, so try something like this:.

$user = App\Request::withCount('status_tracker')
           ->orderBy('status_tracker_count', 'desc')
           ->get();

You can read more about this on official Laravel docs

Note: Your model relationship should be well established in order for this to work, so make sure you have specified the relations between both tables :D

Upvotes: 1

Related Questions