首页 > 解决方案 > 在 Laravel Eloquent 中创建后在方法中返回模型关系/枢轴

问题描述

如何在 a 之后的方法中返回模型及其关系/枢轴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为地点做一个。

标签: laraveleloquent

解决方案


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


推荐阅读