Laravel 使用外键将对象序列化为数组
Laravel serialize object to array with foreign keys
class Customer extends Model
{
public function country(){
return $this->belongsTo(Country::class,'country_id');
}
}
$customer = Customer::Find(1);
在执行 $customer->toArray()
时,它将序列化 'country_id' 而不是整个国家/地区对象。
国家对象是否也可以序列化?
谢谢
您需要明确加载国家/地区关系,
$customer = Customer::findOrFail(1)->load('country');
$customer->toArray()
另一种方法是使用 with
$customers = Customer::with('country')->find(1)->toArray();
如果你想一直加载一个或多个关系,那么你可以在模型中的 protected $with
属性 中指定它们,所以关系总是预加载的,
例如:
protected $with = ['country'];
class Customer extends Model
{
public function country(){
return $this->belongsTo(Country::class,'country_id');
}
}
$customer = Customer::Find(1);
在执行 $customer->toArray()
时,它将序列化 'country_id' 而不是整个国家/地区对象。
国家对象是否也可以序列化?
谢谢
您需要明确加载国家/地区关系,
$customer = Customer::findOrFail(1)->load('country');
$customer->toArray()
另一种方法是使用 with
$customers = Customer::with('country')->find(1)->toArray();
如果你想一直加载一个或多个关系,那么你可以在模型中的 protected $with
属性 中指定它们,所以关系总是预加载的,
例如:
protected $with = ['country'];