laravel - 在 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;
我怎样才能返回$customer
与locations()
?我也会firstOrNew
为地点做一个。
解决方案
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'])
推荐阅读
- ios - Paypal Payment 信用卡支付问题
- c# - 在 asp.net 的 Dropdown 或 RedCombobox 内创建表
- swift - 类型为“Y”的属性“X”不能覆盖类型为“Z”的属性
- javascript - Javascript 手册:`Array.prototype.includes()` 与 `Array.includes()`
- node.js - 按特定顺序缓存和读取文件
- c# - 找不到命名空间名称“OVRGrabbable”的类型统一OVR资产c#统一
- java - 如何在 mongoDB 文档的字段中保留特殊键并删除其中的额外键?
- css - 为什么引导程序有两个容器类?
- r - 如何使用索引为 1 的另一列中的值创建新列
- amazon-web-services - 如何配置 AWS SQS 队列以侦听已创建的 S3 存储桶的事件