Laravel 8.4 MySQL PHP 7.4
I have a Rank model with a ranks table that is related to my User model through the hasmany relationship and User model belongsto the Rank model
Also there is User model that is related to the Post model through the same relationship as above.
I want to get all the posts but is ordered by the ranks of the users who posted it.
so how will I go about writing such query?
I haven't tested this, but this SQL query is probably what you're looking for:
SELECT posts.*, ranks.name AS rank_name, users.id AS user_id FROM posts
JOIN users ON posts.user_id = users.id -- Join the users table with the posts table
JOIN ranks ON users.rank_id = ranks.id -- Join the ranks table with the users table
ORDER BY rank_name;
This query would return each post, along with a "column" called rank_name
containing the rank, and user_id
which would contain the user's id. The ORDER BY
would return the results ordered by the rank name, essentially grouping them together by rank (eg all posts written by a user with "Rank 1" would be put together). You can run it as-is with DB::select
, or here's my approximation with the query builder:
$posts = DB::table('posts')
->select('posts.*', 'ranks.name AS rank_name', 'users.id AS user_id')
->join('users', 'posts.user_id', '=', 'users.id')
->join('ranks', 'users.rank_id', '=', 'ranks.id')
->orderBy('rank_name');
It's also worth pointing out that you don't technically need to use ranks.name AS rank_name
(the same goes for users.id AS user_id
); you could just order directly by ranks.name
. However, I find the former much easier to work with in Laravel.
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.