亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel Eloquent:我的數據透視表有關系

Laravel Eloquent:我的數據透視表有關系

PHP
藍山帝景 2023-03-04 14:18:28
這里有一些關于表格的信息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');

}

希望對你有幫助。


查看完整回答
反對 回復 2023-03-04
?
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']);
}


查看完整回答
反對 回復 2023-03-04
  • 2 回答
  • 0 關注
  • 136 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號