首页 > 解决方案 > 透视列隐藏在模型 Laravel 上

问题描述

我有关系的 Post 模型:

public function prices() {
    return $this->morphedByMany('App\Price', 'postable');
}

我有一个单独的表 postables 与列:

- postable_id
- postable_type
- custom (type: json)

为什么当我想做的时候:$post->pivot->custom我得到空值,为什么?当我在集合中找不到dd($post)列时。custom

标签: phplaravel

解决方案


您必须在定义关系时指定自定义属性,如下所示:

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;
}

推荐阅读