首页 > 解决方案 > Laravel belongsTo 与演员不工作

问题描述

我有模型应用程序和模型属性。
在表应用程序中,我有列:属性(类型 json) 在这些列中,我有属性的 id。例子:

["5", "6", "7"]

此数据在表应用列中attributes

在模型应用程序中,我写了关系:

protected $casts = [
    'attributes' => 'array',
];

public function attribute() {
    return $this->belongsTo('App\Attribute', 'attributes');
}

但我只得到 id 的属性5。但需要获得所有属性。为什么我只得到一个属性?我试过了,hasMany我得到了同样的结果。

标签: laravel

解决方案


我创建了一个带有 JSON 关系的包:https ://github.com/staudenmeir/eloquent-json-relations

您可以像这样创建多对多关系:

class Application extends Model
{
    use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

    protected $casts = [
       'attributes' => 'array'
    ];

    public function attribute()
    {
        return $this->belongsToJson(Attribute::class, 'attributes');
    }
}

class Attribute extends Model
{
    use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

    public function applications()
    {
       return $this->hasManyJson(Application::class, 'attributes');
    }
}

推荐阅读