我想使用 Eloquent 'hasMany' 关系获取与特定颜色相关的所有产品。但是,与产品相关的颜色存储在 json
中。产品表中的值。
颜色表:
-------------
id | color
-------------
1 Black
2 Brown
3 Gray
产品表:
------------------------------
id | name | color
------------------------------
1 Shoe Name ["1","2"]
2 Shoe Name ["2","3"]
颜色模型
public function products()
{
return $this->hasMany(Product::class, 'color');
}
但不幸的是,当我这样做时没有任何返回
dd(Color::products());
我知道问题是试图做一个
hasMany
在 json 字段上,任何帮助或协助都会很棒。不幸的是,我将无法更改数据库结构。我需要照原样处理它。提前致谢。
最佳答案
我创建了一个具有 JSON 关系的包:https://github.com/staudenmeir/eloquent-json-relations
您可以像这样创建多对多关系:
class Product extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'color' => 'json'
];
public function colors()
{
return $this->belongsToJson(Color::class, 'color');
}
}
class Color extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function products()
{
return $this->hasManyJson(Product::class, 'color');
}
}
关于Laravel hasMany 在 json 字段上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47222856/