欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

laravel hasmany orderby 一对多 关系 排序有大用

Laravel orderBy on a relationship

 

I am looping over all comments posted by the Author of a particular post.

foreach($post->user->comments as $comment)
    {
        echo "<li>" . $comment->title . " (" . $comment->post->id . ")</li>";
    }

This gives me

I love this post (3)
This is a comment (5)
This is the second Comment (3)

How would I order by the post_id so that the above list is ordered as 3,3,5

shareimprove this question
 

1 Answer

 

class Category extends Model
{
    public function apps()
    {
        return $this->hasMany('App\App')->orderBy('current_price', 'asc');
    }
}

正确答案

It is possible to extend the relation with query functions:

<?php
public function comments()
{
    return $this->hasMany('Comment')->orderBy('column');
}

[edit after comment]

<?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

class Controller
{
    public function index()
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = User::find(1)->comments()->orderBy($column)->get();

        // use $comments in the template
    }
}

default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )

shareimprove this answer
 
2 
Someone already suggested this on the Laravel Forum, but I want to be able to do this in the Controller so that I can choose which field to sortby based on user input. May be I should I have made this clearer in the question. – PrestonDocks Aug 9 '13 at 12:06
   
I have added a second example – Rob Gordijn Aug 9 '13 at 12:46
1 
Thanks Rob, you put me on the right track. The actual answer was $comments = User::find(10)->comments()->orderBy('post_id')->get(); It seemed to need the get() method in order to work. If you can add get() to your answer I will mark it as the accepted answer. – PrestonDocks Aug 9 '13 at 13:35
2 
This works well if you're retrieving a single record, but if you are retrieving multiple records you'll want something more along the lines of stackoverflow.com/a/26130907/1494454 – dangel Oct 3 '15 at 3:04
   
If you use mysql strict mode, which is default in Laravel 5.4 ,f.ex you'll receive SQLSTATE[42000]: Syntax error or access violation: 1140 Mixing of GROUP columns ... – Sabine Feb 18 at 15:15


来自  https://stackoverflow.com/questions/18143061/laravel-orderby-on-a-relationship
 

Your Answer

普通分类: