急切加载不拉动关系模型
Eager loading not pulling relationship model
Eager loading 没有拉关系模型。
嗨,我正在使用 Laravel 6。我们的数据库是用 Zend 创建的,所以我们的模型有点奇怪;我必须设置主键。
// Customer model
protected $table = 'customer';
protected $primaryKey = 'Customer_ID';
/**
* Get all appointments for the customer.
*/
public function appointments()
{
return $this->hasMany('App\Appointment');
}
然后是约会
protected $table = 'appointment';
protected $primaryKey = 'Appointment_ID';
/**
* Get the customer assigned to this appointment.
*/
public function customer()
{
return $this->belongsTo('App\Customer');
}
现在,在控制器中:
$appointments = App\Appointment::with('customer')->take(5)->get();
return response()->json($appointments, 200);
数组有约会但客户为空:
{... Customer_ID: 1234, customer: null}
有什么想法吗?谢谢
当您在模型中创建关系时,您可以告诉 laravel 哪个字段是外键。
如果你不这样做,laravel 假设外键是 id
,这不是你的情况。
关系的定义应该变成:
public function customer()
{
return $this->belongsTo('App\Customer', 'Customer_ID');
}
Eager loading 没有拉关系模型。
嗨,我正在使用 Laravel 6。我们的数据库是用 Zend 创建的,所以我们的模型有点奇怪;我必须设置主键。
// Customer model
protected $table = 'customer';
protected $primaryKey = 'Customer_ID';
/**
* Get all appointments for the customer.
*/
public function appointments()
{
return $this->hasMany('App\Appointment');
}
然后是约会
protected $table = 'appointment';
protected $primaryKey = 'Appointment_ID';
/**
* Get the customer assigned to this appointment.
*/
public function customer()
{
return $this->belongsTo('App\Customer');
}
现在,在控制器中:
$appointments = App\Appointment::with('customer')->take(5)->get();
return response()->json($appointments, 200);
数组有约会但客户为空:
{... Customer_ID: 1234, customer: null}
有什么想法吗?谢谢
当您在模型中创建关系时,您可以告诉 laravel 哪个字段是外键。
如果你不这样做,laravel 假设外键是 id
,这不是你的情况。
关系的定义应该变成:
public function customer()
{
return $this->belongsTo('App\Customer', 'Customer_ID');
}