问题
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