Davina Leong
Davina Leong

Reputation: 767

Laravel 5 relationship using a 'JSON' column

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?

Upvotes: 0

Views: 2493

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

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

Upvotes: 8

Related Questions