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条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)