Reputation: 551
I would like to order my ticket_replies by date (created_at). Any tipp on how to get the ticket_replies ordered by date (oldest one to the top, newest at least). Did I need to use sortByDesc() or the orderBy() statement? Tabe design:
tickets: |id|supp_id|title|user_id|...
ticket_replies: |id|ticket_id|user_id|text|created_at
files: |id|ticket_replie_id|name
controller:
$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'));
view:
<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>
When I run this code it fails saying:
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)
Did I need to modify my model of ticket_replies for this or did I need to take an other way to get this solved?
Upvotes: 0
Views: 65
Reputation: 149
You should add something like
join("ticket_replies", "ticket.id", "=", "ticket_replies.ticket_id")
to your query. Otherwise you don't get any data from ticket_replies
table, as with()
creates you separate query to select all additional data.
Another option is to take it with with()
subquery:
->with([
'ticket_replies' => function ($query) {
return $query->orderBy('created_at', 'desc');
}
])
depends what do you need.
Upvotes: 1