gpt4 book ai didi

Laravel hasMany 在 json 字段上

转载 作者:行者123 更新时间:2023-12-02 06:50:10 30 4
gpt4 key购买 nike

我想使用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com