在Laravel Eloquent中创建后在方法中返回模型关系/数据透视

时间:2018-06-27 12:57:16

标签: laravel eloquent

如何在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;

如何返回$customerlocations()?我也会为位置做一个firstOrNew

1 个答案:

答案 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'])