如何在firstOrNew
之后的方法中以模型的关系/枢轴返回模型?
型号:
类客户扩展模型 { 受保护的$ table ='customers';
protected $primaryKey = 'customer_id';
public $timestamps = true;
protected $fillable = [
'email',
'first_name',
'last_name',
'address',
'city',
'county',
'country',
'phone',
'organization_id',
'unique_value'
];
protected $guarded = [];
public function locations()
{
return $this->belongsToMany('App\Models\CustomerLocations', 'customer_customer_locations', 'customer_id', 'address_id')->withTimestamps();
}
}
方法:
$customer = Customer::firstOrNew(['unique_value' => $unique_code]);
做一些逻辑... 和
return $customer;
如何返回$customer
和locations()
?我也会为位置做一个firstOrNew
。
答案 0 :(得分:1)
在模型中使用protected $appends = ['locations'];
。
protected $primaryKey = 'customer_id';
public $timestamps = true;
protected $appends = ['locations'];
protected $fillable = [
'email',
'first_name',
'last_name',
'address',
'city',
'county',
'country',
'phone',
'organization_id',
'unique_value'
];
protected $guarded = [];
public function locations()
{
return $this->belongsToMany('App\Models\CustomerLocations', 'customer_customer_locations', 'customer_id', 'address_id')->withTimestamps();
}
或者您使用return $cusotmer->load(['locations'])