[英]Laravel 6.x relation set default value on delete on relationship partner
[英]Laravel 6.x manipulate relationship data as attribute
在laravel中是否可以通過關系創建自己的屬性?
例如:Customer 與 CustomerAddress 有關系。 現在我想獲取所有有關系的客戶,然后在客戶上獲得屬性address
。 address
字段將使用customer_address
表的多列生成。
customer_address
表有列street
, state
,它們應該連接到客戶模型上的address
。
$customer = \App\Customer::with("customerAddress")->get();
return $customer->address;
>> street.state
這可能嗎,toArray() 和 toJSON() 不會忽略這些自定義屬性?
確保您的模型中有正確的關系,然后定義一個返回自定義屬性的方法,然后將其添加到$appends
數組中
Customer
class Customer extends Model
{
protected $appends = ['custom_attribute'];
public function addresses()
{
return $this->hasMany(CustomerAddress::class, 'customer_id');
}
public function getCustomAttribute() {
return 'some calculated data';
}
}
CustomerAddress
class CustomerAddress extends Model
{
protected $appends = ['custom_attribute'];
public function customer()
{
return $this->belongsTo(Customer::class, 'customer_id');
}
public function getCustomAttribute() {
return 'some calculated data';
}
}
請注意,屬性名稱是sneak_case,而方法名稱是在StudlyCase 中以get
為前綴(這最終使其成為camelCase)。 方法名稱和訪問器名稱必須匹配。
現在在您的控制器中,您可以獲得所有客戶及其地址。
$customers = Customer::with("addresses:street,state")->get();
如果您訪問$customers
您將看到所有客戶及其地址。 現在您可以使用自定義屬性返回自定義值。
例子:
public function getCustomAttribute() {
return "{$this->street} {$this->state}";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.