I have an issue with Eager Loading using the below code.
Issue is with the Status model
$ticket = Ticket::where('id', $id)->with(['customer', 'status', 'notes' => function($query) {
$query->orderBy('updated_at', 'desc');
}])->first();
If I do,
return response()->json($ticket);
I get the expected response, all OK
{"id":1,"customer_id":10001,"ztk_ticket_no":"ZTK0000001","status":{"id":1,"value":"Open","deleted_at":null,"created_at":"2016-02-13 01:36:20","updated_at":"2016-02-13 01:36:20"},"deleted_at":null,"created_at":"2016-02-13 01:36:20","updated_at":"2016-02-13 01:36:20","customer":{"id":1,"customer_id":10001,"title":"Test Company","deleted_at":null,"created_at":"2016-02-13 01:36:20","updated_at":"2016-02-13 01:36:20"},"notes":[{"id":1,"ticket_id":1,"note":"Lorem ipsum dolor sit amet, ","status":1,"deleted_at":null,"created_at":"2016-02-13 01:36:20","updated_at":"2016-02-13 01:36:20"}]}
But if I do
return response()->json($ticket->status);
I get the id of the status, not the Model
1
Status Model:
class Status extends Model
{
protected $table = 'statuses';
}
Ticket Model:
class Ticket extends Model
{
public function status() {
return $this->hasOne('App\Status', 'id', 'status');
}
}
According to your relationship definition, it looks like your
Ticketmodel has a field namedstatus. If you have a field name on your model with the same name as one of your relationship methods, when you do$ticket->status, you are going to get the value of field, not the related object.So, based on what I can see, it looks like your
tickets.statusfield is a foreign key to thestatusestable. If this is the case, then there are a few issues.First, your
statusfield should be renamed tostatus_id. This will help remove the ambiguity between the field name and the related object.Second, since your Ticket model contains the foreign key, it is on the
belongsToside of the relationship. It may sound a little weird, but aStatuscan have manyTickets, but aTicketbelongs to aStatus. So, you need to change yourstatus()relationship fromhasOnetobelongsTo.If you rename the
statusfield tostatus_id, you can change your method to this:With this, you access the id field with
$ticket->status_id, and the relatedStatusobject with$ticket->status.If you can't change your
statusfield, then it would be a good idea to rename yourstatus()relationship method, so your method should look something like this:With this, you access the id field with
$ticket->status, and the related status object with$ticket->relatedStatus.