Programing

Laravel orderBy 관계에

lottogame 2020. 8. 26. 08:19
반응형

Laravel orderBy 관계에


특정 게시물의 작성자가 게시 한 모든 댓글을 반복합니다.

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

이것은 나에게 준다

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

위의 목록이 3,3,5로 정렬되도록 post_id로 어떻게 주문합니까?


쿼리 함수로 관계를 확장 할 수 있습니다.

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

[댓글 후 편집]

<?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
    }
}

기본 사용자 모델 + 간단한 컨트롤러 예; 주석 목록을 가져올 때 Input :: get ()을 기반으로 orderBy ()를 적용하십시오. (일부 입력 확인을 수행하십시오;))

참고 URL : https://stackoverflow.com/questions/18143061/laravel-orderby-on-a-relationship

반응형