0
votes

How to sum one-to-one polymorphic relationship column through hasMany relationship in Laravel?

Owner model

public function capitals()
{
    return $this->hasMany('App\Capital');
}

Capital model

public function transaction()
{
    return $this->morphOne('App\Transaction', 'transacable');
}

Transaction model

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

I want the owner to have-many transactions through capital, something like this:

Owner model

public function transactions()
{
   return $this->hasManyThrough('App\Transaction', 'App\Capital', 'transacable_id')->where('transacable_type', 'App\Capital');
}

But I cannot get a relationship to work. and get this error.

Column not found: 1054 Unknown column 'capitals.transacable_id' in 'field list'

1

1 Answers

1
votes

Put the transacable_id in the right position:

public function transactions()
{
   return $this->hasManyThrough(
            'App\Transaction',
            'App\Capital',
            'owner_id', // Foreign key on capitals table...
            'transacable_id', // Foreign key on transactions table...
            'id', // Local key on owners table...
            'id' // Local key on capitals table...
        )->where('transacable_type', 'App\Capital');
}