[英]Laravel Eloquent: My Pivot table has relation
這里有一些關於表的信息
User table
-id
-name
UserProduct table
-id
-user_id
-product_id
Product table
-id
-name
Contribution
-id
-user_product_id
-contribution
用戶 Model
public function products()
{
return $this->belongsToMany('App\Product');
}
產品 Model
public function users()
{
return $this->belongsToMany('App\User');
}
用戶產品 Pivot Model
use Illuminate\Database\Eloquent\Relations\Pivot;
class UserProduct extends Pivot
{
public function contribution()
{
return $this->hasMany('App\Contribution');
}
}
我嘗試像auth()->user()->products()->first()->pivot->contribution()
但它給出了一些錯誤。
調用未定義的方法 Illuminate\Database\Eloquent\Relations\Pivot::contribution()
您能否使用自定義 pivot 表 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');
}
希望它可以幫助你。
受到這個問題的啟發。 我們不能在 pivot object 上調用 function。
首先,將UserProduct添加到別名中,以便我們可以在Blade中調用它。
配置\app.php:
'aliases' => [
'UserProduct' => App\UserProduct::class,
],
然后,使用find function 然后調用關系function
刀:
@foreach ($product->users as $user)
@foreach (UserProduct::find($user->pivot->id)->contribution()->get() as $contribution)
// viewing contribution attribute
@endforeach
@endforeach
不要忘記包含 pivot id
產品 Model:
public function users()
{
return $this->belongsToMany('App\User')
->withPivot(['id']);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.