Laravel Eloquent:我的数据透视表有关系

这里有一些关于表格的信息


User table

-id

-name


UserProduct table

-id

-user_id

-product_id


Product table

-id

-name


Contribution

-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()


蓝山帝景
浏览 79回答 2
2回答

POPMUISE

你可以使用自定义数据透视表模型吗?class UserProduct extends Pivot{  public function contribution()  {    return $this->belongsTo('App\Contribution');  }}// User modelpublic function products(){    return $this->belongsToMany('App\Product')->using('App\UserProduct');}希望对你有帮助。

MM们

我们不能在枢轴对象上调用函数。解决方案是:首先,将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']); }
打开App,查看更多内容
随时随地看视频慕课网APP