【发布时间】:2020-01-21 21:35:08
【问题描述】:
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}
有什么想法吗?谢谢
【问题讨论】:
-
客户的约会表的外键是哪个?
-
这似乎很明显,但您肯定有您正在查询的约会的客户记录吗?
-
@GiacomoM 将是“Customer_ID”。它显示在约会结果中,因此关联就在那里。
-
@GBWDev 是的,但它显示为空。我迷路了。
-
尝试在关系上指定主键、外键和表