duanguan3863 2014-06-08 11:58
浏览 6
已采纳

laravel 4:模板中的订单对象

I'm trying to order the tests for each user in descending order of created_at. I tried it in the template but I didn't succeed. These are my tables:

 | users      |   | courses    |    | tests      |
 | ---------- |   |------------|    |------------|
 | id         |   | id         |    | id         |
 | name       |   | name       |    | name       |
 | created_at |   | created_at |    | created_at |
                  | user_id    |    | course_id  |

A user has many courses and a course has many tests. I'll like to order all the tests in descending order of created_at.

I tried this in my template:

@foreach(User::find($user->id)->courses as $course)
        @foreach(Course::find($course->id)->tests as $test)
            <p>Name: {{$test->name}}</p>
            <p>Date: {{$test->created_at}}</p>
        @endforeach
@endforeach

Edit: There are my models

User.php

   public function courses()
   {
    return $this->hasMany('Course');
   }

Course.php

   public function user()
    {
    return $this->belongsTo('User');
    }

   public function test()
    {
    return $this->hasMany('Test');
    }

Test.php

   public function courses()
    {
    return $this->belongsTo('Course');
    }
  • 写回答

2条回答 默认 最新

  • dongtao9887 2014-06-08 16:25
    关注

    You may try this, do it in your Controller:

    $users = User::with(array('courses.tests' => function($query) {
        $query->orderBy('tests.created_at', 'desc');
    }))->find($user->id);
    

    Then load the view and pass the $user object like this:

    return View::make('your_view_name')->withuser($user);
    

    Then in your view try something like this:

    @foreach($user->courses->tests as $test)
            <p>Name: {{ $test->name }}</p>
            <p>Date: {{ $test->created_at }}</p>
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?