简体   繁体   中英

Laravel Eloquent: My Pivot table has relation

Here some information about the table

User table
-id
-name

UserProduct table
-id
-user_id
-product_id

Product table
-id
-name

Contribution
-id
-user_product_id
-contribution

User Model

public function products()
{
    return $this->belongsToMany('App\Product');
}

Product Model

public function users()
{
    return $this->belongsToMany('App\User');
}

UserProduct Pivot Model

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserProduct extends Pivot

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

I try like auth()->user()->products()->first()->pivot->contribution() but it gives some error.

Call to undefined method Illuminate\Database\Eloquent\Relations\Pivot::contribution()

could you maybe use custom pivot table model .

class UserProduct extends Pivot
{
  public function contribution()
  {
    return $this->belongsTo('App\Contribution');
  }
}
// User model

public function products()
{
    return $this->belongsToMany('App\Product')->using('App\UserProduct');
}

Hope it helps you.

Inspired by this problem. We cannot call function on pivot object.

The solution was:

First, add UserProduct to aliases so we can call it in blade .

config\app.php:

'aliases' => [
   'UserProduct' => App\UserProduct::class, 
],

Then, use find function then call the relation function

Blade:

@foreach ($product->users as $user)
    @foreach (UserProduct::find($user->pivot->id)->contribution()->get() as $contribution)
         // viewing contribution attribute
    @endforeach
@endforeach

Don't forget to include pivot id

Product Model:

public function users()
{
    return $this->belongsToMany('App\User')
                ->withPivot(['id']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM