這里有一些關于表格的信息User table-id-nameUserProduct table-id-user_id-product_idProduct table-id-nameContribution-id-user_product_id-contribution用戶模型public function products(){ return $this->belongsToMany('App\Product');}產品型號public function users(){ return $this->belongsToMany('App\User');}用戶產品樞軸模型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()
2 回答

POPMUISE
TA貢獻1765條經驗 獲得超5個贊
你可以使用自定義數據透視表模型嗎?
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');
}
希望對你有幫助。

MM們
TA貢獻1886條經驗 獲得超2個贊
我們不能在樞軸對象上調用函數。
解決方案是:
首先,將UserProduct添加到別名中,以便我們可以在blade中調用它。
配置\應用程序.php :
'aliases'?=>?[? ??'UserProduct'?=>?App\UserProduct::class,? ],
然后,使用查找函數然后調用關系函數
刀刃 :
@foreach?($product->users?as?$user) ????@foreach?(UserProduct::find($user->pivot->id)->contribution()->get()?as?$contribution)? ????????????//?viewing?contribution?attribute ????@endforeach ????@endforeach
不要忘記包含數據透視表 ID
產品型號:
public?function?users(){??? ?return?$this->belongsToMany('App\User') ????????????????->withPivot(['id']); }
- 2 回答
- 0 關注
- 136 瀏覽
添加回答
舉報
0/150
提交
取消