Laravel 5 relationship using a 'JSON' column

僤鯓⒐⒋嵵緔 提交于 2021-01-29 09:13:34

问题


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?

If it is, how so?

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"}

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


回答1:


Laravel has no native support for JSON relationships.

I created a package for this: https://github.com/staudenmeir/eloquent-json-relations

You can use it like this:

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');
    }
}


来源:https://stackoverflow.com/questions/53878743/laravel-5-relationship-using-a-json-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!