laravel5.1按日期排序的结果(created_at)

时间:2016-02-01 13:40:01

标签: mysql eloquent sql-order-by laravel-5.1

我想按日期(created_at)订购我的ticket_replies。有关如何获取按日期排序的ticket_replies的任何内容(最旧的一个到顶部,至少是最新的)。我需要使用sortByDesc()还是orderBy()语句? Tabe设计:

tickets: |id|supp_id|title|user_id|...

ticket_replies: |id|ticket_id|user_id|text|created_at

files: |id|ticket_replie_id|name

控制器:

            $ticket = Auth::user()->tickets()->join("ticket_replies", "ticket.id", "=", "ticket_replies.ticket_id")->where('id', $id)->with(['ticket_replie.file'])->orderBy('ticket_replies.created_at')->firstOrFail();

return view('protected.ticketDetail', compact('ticket'));

视图:

<div class="container">

ID: {{$ticket->id}}
title: {{ $ticket->title}}<br>
status: {{ returnStatus($ticket->status) }}<br>
Ticket created: {{ $ticket->created_at }}<br>


@if (!$ticket->supporter)
    supporter:-<br></br></br>
@else
    supporter  {{ $ticket->supporter->username }}<br></br>
@endif

@foreach($ticket->ticket_replie as $reply)
    @if ($reply->file == null)
        reply text: {{ $reply->text }}</br>
    @else
        reply text: {{ $reply->text }}</br>
        file: <a href="/path/to/file/{!! $reply->file->name !!}">Download file</a><br>
    @endif
reply created at: {{$reply->created_at}}</br></br>
@endforeach 

</div>

当我运行此代码时,它无法说:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `tickets` inner join `ticket_replies` on `ticket`.`id` = `ticket_replies`.`ticket_id` where `tickets`.`user_id` = 1 and `tickets`.`user_id` is not null and `id` = 43 order by `ticket_replies`.`created_at` asc limit 1)

我是否需要为此修改我的ticket_replies模型,或者我是否需要采取其他方式来解决这个问题?

1 个答案:

答案 0 :(得分:1)

您应该添加类似

的内容
join("ticket_replies", "ticket.id", "=", "ticket_replies.ticket_id")

到你的查询。否则,您无法从ticket_replies表中获取任何数据,因为with()会创建单独的查询以选择所有其他数据。

另一种选择是使用with()子查询:

->with([
                'ticket_replies' => function ($query) {
                    return $query->orderBy('created_at', 'desc');
                }
            ])

取决于你需要什么。