0

Eager loading not pulling relation model.

Hi, Im using Laravel 6. Our database was created with Zend so our model is a bit strange; I have to set the primary keys.


// Customer model

protected $table = 'customer';
protected $primaryKey = 'Customer_ID';

/**
 * Get all appointments for the customer.
 */
public function appointments()
{
    return $this->hasMany('App\Appointment');
}

Then for the appointments


protected $table = 'appointment';
protected $primaryKey = 'Appointment_ID';

/**
 * Get the customer assigned to this appointment.
 */
public function customer()
{
    return $this->belongsTo('App\Customer');
}

Now, in a controller:

$appointments = App\Appointment::with('customer')->take(5)->get();
return response()->json($appointments, 200);

The array has the appointments but customer is null:

{... Customer_ID: 1234, customer: null}

Any ideas? Thanks

Sylar
  • 11,422
  • 25
  • 93
  • 166

1 Answers1

1

When you create the relationship in the model, you can tell laravel which is the field of the foreign key.
If you do not do it, laravel supposes the foreign key is id, which is not your case.

The definition of the relationship should becomes:

public function customer()
{
    return $this->belongsTo('App\Customer', 'Customer_ID');
}
Giacomo M
  • 4,450
  • 7
  • 28
  • 57