Home > Mobile >  How to get a column relationship based on field
How to get a column relationship based on field

Time:04-27

I have a chat table that both a user and admin can chat the table is defined as follow:

id, from_id, to_id, message, is_from_admin.

what I want is, if the is_from_admin is true laravel should use the admin table at sql level for the from. otherwise it should use the user table for from and same applies to the to field. Thanks

CodePudding user response:

Laravel can not solve what you are doing, which is a polymorphic relationship, based on a boolean. Theoretically you could bind the polymorphic class definition to 0 or 1, but this is a hack at best.

Instead i would create two relationships combined with some logic in an accessor. Create a relationship for the admin and for the user.

Chat extends Model
{
    public function fromAdmin()
    {
        return $this->belongsTo(Admin::class, 'from_id')->where('is_from_admin', true);
    }

    public function fromAdmin()
    {
        return $this->belongsTo(User::class, 'from_id')->where('is_from_admin', false);
    }
}

Now create the accessor on the Chat model, using your new relationships.

public function getFromAttribute()
{
    return $this->fromAdmin ?? $this->fromUser;
}

With this approach, you should be able to access the attribute like this.

Chat::find(1)->from; // either a user or admin based on the data.

CodePudding user response:

If you have the chance, I'd rework the table a bit and name it like so:

id, from_user_type, from_user_id, to_user_id, message

The pair from_user_type and from_user_id can be used to creat a custom polymorphic relation ("type" refers to the model/table name, and "id" refers to the id of a row in this table) as seen here: https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-polymorphic-relations .

If you also want to send admin-to-admin, you should also add to_user_type, to_user_id so you can create a polymorphic relationship on the receiving side as well.

The polymorphic relation will look something like this:

class ChatMessage
{
    public function fromUser()
    {
        // This function should automatically infer `from_user_type` and `from_user_id`
        // from this function name.
        return $this->morphTo();
    }
}

class AdminUser
{
    public function chatMessages()
    {
        return $this->morphMany(ChatMessage::class, 'fromUser');
    }
}
  • Related