php - 透视列隐藏在模型 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
解决方案
您必须在定义关系时指定自定义属性,如下所示:
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;
}
推荐阅读
- python-3.x - 如何使用 Sublime Text 编译 Python 3 程序
- c++ - 非静态成员引用必须相对于特定对象
- java - Android / JAVA:根据时区获取当前时间
- vue.js - Vuejs - 如何将新值添加到 itemList 数组中
- java - spring data - mongoDB - 为什么要创建多个对象?
- react-native - 我如何对表格进行分页
- python - 错误:“dagster.core.types.runtime”不是包
- python - TypeError:不能在 Python 中的字节类对象上使用字符串模式
- awesome-wm - 将 awesome.client.iterate 限制为单个标签
- css - 将 css 变量分配给 scss 变量