首先,以Json列的形式存储一对多关系是一个好主意,如果是这样,我如何在laravel中编写查询以检索数据
前:
我的活动表和垂直表
活动表
id | activity | verticals
1 | Dusting | [1,2]
2 | Oiling | [3]
3 | Mopping | [1,2,3]
垂直表
id | vertical
1 | House Keeping
2 | Pantry
3 | Engineering & Machinery
现在在我的仪表板中显示活动列表,结果应为
id | activity | verticals
1 | Dusting | Housekeeping, Pantry
2 | Oiling | Engineering & Machinery
3 | Mopping | Housekeeping, Pantry, Engineering & Machinery
现在,在传统的非json方法中,我使用了lalovel Eloquent的 self :: hasMany 但是如果使用json,我可以这样做
也是可取的吗?
答案 0 :(得分:0)
我创建了一个具有JSON关系的软件包:https://github.com/staudenmeir/eloquent-json-relations
您可以像这样创建多对多关系:
class Activity extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'verticals' => 'json',
];
public function vertical()
{
return $this->belongsToJson(Vertical::class, 'verticals');
}
}
class Vertical extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function activities()
{
return $this->hasManyJson(Activity::class, 'verticals');
}
}