【问题标题】:Laravel Eloquent: My Pivot table has relationLaravel Eloquent:我的数据透视表有关系
【发布时间】:2020-08-22 21:43:51
【问题描述】:

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

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

UserProduct 透视模型

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以使用custom pivot table 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');
    }
    

    希望对你有帮助。

    【讨论】:

    【解决方案2】:

    this 问题的启发。我们不能在枢轴对象上调用函数。

    解决办法是:

    首先,将 UserProduct 添加到 aliases,以便我们可以在 blade 中调用它。

    配置\app.php:

    'aliases' => [
       'UserProduct' => App\UserProduct::class, 
    ],
    

    然后,使用 find 函数然后调用 relation 函数

    刀片:

    @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-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-07
      • 2017-07-22
      • 1970-01-01
      • 2014-09-29
      相关资源
      最近更新 更多