2

I have a scenario that needs two polymorphic relationship in one model. The main model is Calls which includes a Caller and Callee. Caller and Callee can be a User, Buyer or Seller. So I designed my table like following.

enter image description here

class Call extends Model
{
    public function caller()
    {
       return $this->morphTo();
    }

    public function callee()
    {
      return $this->morphTo();
    }
}

I created my User model like this

class User extends Authenticatable
{
    public function buyers()
    {
        return $this->hasMany(Buyer::class);
    }

    public function outgoingCalls()
    {
        return $this->morphMany(self::class, 'caller');
    }

    public function incomingCalls()
    {
        return $this->morphMany(self::class, 'callee');
    }
}

and created my Buyer and Seller models like,

class Buyer extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function outgoingCalls()
    {
        return $this->morphMany(self::class, 'caller');
    }

    public function incomingCalls()
    {
        return $this->morphMany(self::class, 'callee');
    }
}

So, I want save a call when a User calls a Buyer like this

Auth::user()->buyers()->find($args['buyer_id'])->outgoingCalls()->save()

and save a call when a Buyer or Seller calls to User

Buyer::find(2)->user()->outgoingCalls()->save()

my problem is I couldn't make it work like I wanted so I had to do it like this,

        $userCall = new UserCall([
            'caller_id' => Auth::user()->id,
            'caller_type' => User::class,
            'status' => 1,
            'started_at' => '2020-06-24 01:00:00',
            'ended_at' => '2020-06-24 02:00:00',
        ]);

        if (Auth::user()->buyers()->find($args['buyer_id'])->incomingCalls()->save($userCall)) {
            return [
                'status' => 'SUCCESS',
                'message' => 'User Call successfully saved',
            ];
        }

could you please help me figure out this problem ? Thank you in advance !

Can Atuf Kansu
  • 523
  • 2
  • 7
  • 16

0 Answers0