[英]How to insert data into a pivot table with columns belonging to same model in Laravel?
[英]Pivot columns is hidden on model Laravel
我有關系的郵政模型:
public function prices() {
return $this->morphedByMany('App\Price', 'postable');
}
我有一個單獨的表postables與列:
- postable_id
- postable_type
- custom (type: json)
為什么要在需要時: $post->pivot->custom
我得到null,為什么? 當我做dd($post)
列custom
在集合中找不到。
定義關系時必須指定自定義屬性,如下所示:
public function prices() {
return $this->morphedByMany('App\Price', 'postable')->withPivot('custom');
}
如果要轉換自定義屬性,則必須為數據透視表創建一個模型,如下所示:
use Illuminate\Database\Eloquent\Relations\Pivot;
class Postable extends Pivot
{
protected $casts = [
'custom' => 'array',
];
}
在您的關系定義中引用此模型:
return $this->morphedByMany('App\Price', 'postable')
->using('App\Postable')
->withPivot('custom');
現在,您可以像這樣檢索值:
foreach ($post->prices as $price) {
echo $price->pivot->custom;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.