I want to call relation into accessors function with less query
ticket has many messages
ticket model has accessors function
I want into accessors function if ticket->messages()->exist() == TRUE returns messages body, or ** if ticket->messages()->exist() == TRUE** returns ticket
s body
this line code ($ticket->last_body) in view make one Query for each row and i want to decrease my query
Ticket model:
class Ticket extends Model
{
public function messages()
{
return $this->hasMany(TicketMessage::class, 'ticket_id');
}
public function getLastBodyAttribute()
{
if($this->messages()->exists()){
return $this->messages()->orderByDesc('created_at')->first()->body;
} else {
return $this->body;
}
}
}
Ticket massage belongsto tickets
TicketMessage model :
class TicketMessage extends Model
{
public function ticket()
{
return $this->belongsTo(Ticket::class,'ticket_id');
}
}
I get tickets with own relationships and passed to view TicketController:
class TicketController extends Controller
{
public function index(Request $request)
{
$tickets = Ticket::with('messages')
->where('status', 'open')
->get();
return view('ticket::supporter.supporter', compact('tickets'));
}
}
this line code $ticket->last_body make one Query for each row and i want to decrease my query
**supporter.blade** :
@foreach($tickets as $ticket)
<a href="{{url(Route('show_client_ticket', ['id' => $ticket->id]))}}">
{{$ticket->subject}}
</a>
<p style="color: #959A9D;">
{{$ticket->last_body}} //this line returns too much Query
</p>
<hr>
@endforeach