[英]Laravel/PHP MySQL One to Many Relationship using Json
Firstly is it a good idea to store one to many relationships in the form of a Json column and if so how do I write the query in laravel to retrieve the data 首先,以Json列的形式存储一对多关系是一个好主意,如果是这样,我如何在laravel中编写查询以检索数据
Ex : 例如:
I've activities table and verticals table 我有活动表和垂直表
Activities Table 活动表
id | activity | verticals
1 | Dusting | [1,2]
2 | Oiling | [3]
3 | Mopping | [1,2,3]
Verticals Table 垂直表
id | vertical
1 | House Keeping
2 | Pantry
3 | Engineering & Machinery
Now in my dashboard showing activities list the result should be 现在在我的仪表板中显示活动列表,结果应该是
id | activity | verticals
1 | Dusting | Housekeeping, Pantry
2 | Oiling | Engineering & Machinery
3 | Mopping | Housekeeping, Pantry, Engineering & Machinery
Now in the traditional non json method I'd have used laravel Eloquent's self::hasMany But can i do this same if using json 现在在传统的非json方法中我已经使用了laravel Eloquent的self :: hasMany但是如果使用json我可以这样做吗
also is it advisable ? 也是可取的吗?
I created a package with JSON relationships: https://github.com/staudenmeir/eloquent-json-relations 我创建了一个包含JSON关系的包: https : //github.com/staudenmeir/eloquent-json-relations
You can create a many-to-many relationship like this: 您可以创建这样的多对多关系:
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');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.