【问题标题】:Laravel 5 relationship using a 'JSON' column使用“JSON”列的 Laravel 5 关系
【发布时间】:2019-05-21 13:39:57
【问题描述】:

是否可以在 Laravel 5 中使用 Eloquent 创建关系,其中外键存在于 JSON 列的字段中?

如果是,那是怎么回事?

示例: 我有一个名为chats 的表,其中包含participantIds 列,数据类型为JSON。数据的JSON 格式如下所示:

{"creator": "1", "recipient": "2"}

我想使用这些字段加入users 表以获取聊天的参与者。 我该怎么做?

【问题讨论】:

    标签: json database laravel-5 eloquent php-7


    【解决方案1】:

    Laravel 不支持 JSON 关系。

    我为此创建了一个包:https://github.com/staudenmeir/eloquent-json-relations

    你可以这样使用它:

    class Chat extends Model
    {
        use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
    
        protected $casts = [
           'participantIds' => 'json',
        ];
    
        public function creator()
        {
            return $this->belongsTo(User::class, 'participantIds->creator');
        }
    
        public function recipient()
        {
            return $this->belongsTo(User::class, 'participantIds->recipient');
        }
    }
    
    class User extends Model
    {
        use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
    
        public function createdChats()
        {
           return $this->hasMany(Chat::class, 'participantIds->creator');
        }
    
        public function receivedChats()
        {
           return $this->hasMany(Chat::class, 'participantIds->recipient');
        }
    }
    

    【讨论】:

    • 我整天都在努力使用这么好的包。但我收到以下错误:需要 php ^7.2.5 || ^8.0 -> 您的 php 版本(7.2;通过 config.platform 覆盖,实际:7.2.5)不满足该要求。
    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多