简体   繁体   English

枢轴列在模型Laravel中隐藏

[英]Pivot columns is hidden on model Laravel

I have Post model with relation: 我有关系的邮政模型:

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

I have a separate table postables with columns: 我有一个单独的表postables与列:

- postable_id
- postable_type
- custom (type: json)

Why when I want do: $post->pivot->custom I get null, why? 为什么要在需要时: $post->pivot->custom我得到null,为什么? When I do dd($post) column custom not found in collection. 当我做dd($post)custom在集合中找不到。

You have to specify the custom attributes when you define the relation, like this: 定义关系时必须指定自定义属性,如下所示:

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

If you want to cast the custom attribute, you would have to create a model for the pivot table, like this: 如果要转换自定义属性,则必须为数据透视表创建一个模型,如下所示:

use Illuminate\Database\Eloquent\Relations\Pivot;

class Postable extends Pivot
{
    protected $casts = [
        'custom' => 'array',
    ];
}

Reference this model in your relation definition: 在您的关系定义中引用此模型:

return $this->morphedByMany('App\Price', 'postable')
    ->using('App\Postable')
    ->withPivot('custom');

Now you can retrieve the value like this: 现在,您可以像这样检索值:

foreach ($post->prices as $price) {
    echo $price->pivot->custom;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM