Laravel 5使用'JSON'列的关系 [英] Laravel 5 relationship using a 'JSON' column

查看:116
本文介绍了Laravel 5使用'JSON'列的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to use Eloquent to create a relationship in Laravel 5 where the foreign key exists in a field in a JSON column?

如果是,怎么办?

示例:我有一个名为 chats 的表,该表具有 JSON 数据类型的 participantIds 列.数据的 JSON 格式如下:

Example: I have a table called chats with a participantIds column, of a JSON datatype. The JSON format of the data looks like this:

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

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

I want to join the users table using those fields to get the participants of the Chats. How do I do that?

推荐答案

Laravel不支持JSON关系.

Laravel has no native support for JSON relationships.

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

I created a package for this: 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');
    }
}

这篇关于Laravel 5使用'JSON'列的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆