首页 > 解决方案 > 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()

标签: phplaraveleloquent

解决方案


你可以使用自定义数据透视表模型吗?

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');
}

希望它可以帮助你。


推荐阅读