Laravel 在 json 字段上有很多
Laravel hasMany on json field
我想使用 Eloquent 'hasMany' 关系获取与某种颜色相关的所有产品。然而,与产品相关的颜色存储在产品 table.
中的 json
值中
颜色Table:
-------------
id | color
-------------
1 Black
2 Brown
3 Gray
产品Table:
------------------------------
id | name | color
------------------------------
1 Shoe Name ["1","2"]
2 Shoe Name ["2","3"]
颜色模型
public function products()
{
return $this->hasMany(Product::class, 'color');
}
但不幸的是 returns 当我这样做时
dd(Color::products());
我知道问题是试图在 json 字段上执行 hasMany
,任何帮助或协助都会很好。不幸的是,我无法更改数据库结构。我需要按原样使用它。
提前致谢。
继续我的评论,理想情况下我会简单地执行以下操作:
- 创建一个名为
product_colors
的枢轴 table 来存储产品和颜色关联。所以关系将变成多对多。
这是我强烈推荐的。由于您已经写过您无法更改数据库结构。
例如,检索某种颜色的产品列表。您的解决方案可能如下所示:
在您的 Product 模型中创建一个将颜色 json 字段转换为数组的修改器:
public function setColor()
{
return json_decode($this->color, true);
}
在您的 Color 模型中创建一个函数来检索所有产品的列表,然后将列表过滤为 return 个包含特定颜色的产品
public function products()
{
return Product::all()->filter(function($product) {
return in_array($this->id, $product->color)) ? $product : null;
});
}
我创建了一个包含 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');
}
}
我想使用 Eloquent 'hasMany' 关系获取与某种颜色相关的所有产品。然而,与产品相关的颜色存储在产品 table.
中的json
值中
颜色Table:
-------------
id | color
-------------
1 Black
2 Brown
3 Gray
产品Table:
------------------------------
id | name | color
------------------------------
1 Shoe Name ["1","2"]
2 Shoe Name ["2","3"]
颜色模型
public function products()
{
return $this->hasMany(Product::class, 'color');
}
但不幸的是 returns 当我这样做时
dd(Color::products());
我知道问题是试图在 json 字段上执行 hasMany
,任何帮助或协助都会很好。不幸的是,我无法更改数据库结构。我需要按原样使用它。
提前致谢。
继续我的评论,理想情况下我会简单地执行以下操作:
- 创建一个名为
product_colors
的枢轴 table 来存储产品和颜色关联。所以关系将变成多对多。
这是我强烈推荐的。由于您已经写过您无法更改数据库结构。
例如,检索某种颜色的产品列表。您的解决方案可能如下所示:
在您的 Product 模型中创建一个将颜色 json 字段转换为数组的修改器:
public function setColor()
{
return json_decode($this->color, true);
}
在您的 Color 模型中创建一个函数来检索所有产品的列表,然后将列表过滤为 return 个包含特定颜色的产品
public function products()
{
return Product::all()->filter(function($product) {
return in_array($this->id, $product->color)) ? $product : null;
});
}
我创建了一个包含 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');
}
}