我想按日期(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模型,或者是否需要采取其他方法解决此问题?

最佳答案

您应该添加类似

join("ticket_replies", "ticket.id", "=", "ticket_replies.ticket_id")


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

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

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


取决于您需要什么。

关于mysql - laravel5.1按日期排序结果(created_at),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35131994/

10-15 02:47