不能使用 belongsToMany 同步数据透视表

Cannot use belongsToMany to sync pivot data

我有一个名为 invite_riskarea_riskfield 的枢轴 table,它定义了与 invite table:

的关系

我需要做的是同步多个 invite_riskarea_riskfield 权限(插入、编辑、查看)。所以我尝试在Invite模型中设置如下关系:

public function permissions()
{
    return $this->belongsToMany(
        InviteRiskareaRiskfield::class,
        'invites',
        'id',
        'id'
    );
}

所以我应该可以做到$invite->permissions()->sync($permissions);

但是关系returns这个错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'invite_riskarea_riskfield.id' in 'on clause' (SQL: select invite_riskarea_riskfield.*, invites.id as pivot_id from invite_riskarea_riskfield inner join invites on invite_riskarea_riskfield.id = invites.id where invites.id = 17)

我做错了什么?

假设您的模型是:

  • Invite (invites table)
  • RiskAreaRiskField (riskarea_riskfield table)
  • InviteRiskareaRiskfield (invite_riskarea_riskfield table).

你们的关系应该是这样的。请随意将方法名称更改为对您来说更有意义的名称。

class Invite extends Model
{
    public function invite_riskarea_riskfield()
    {
        return $this->hasMany(InviteRiskAreaRiskField::class, 'invite_id');
    }

    public function riskarea_riskfield()
    {
        return $this->belongsToMany(RiskAreaRiskField::class, 'invite_riskarea_riskfield', 'invite_id', 'riskarea_riskfield_id')
                    ->withPivot(['insert', 'edit', 'view'])
                    ->using(InviteRiskAreaRiskField::class);
    }
}
class RiskAreaRiskField extends Model
{
    public function invite_riskarea_riskfield()
    {
        return $this->hasMany(InviteRiskAreaRiskField::class, 'riskarea_riskfield_id');
    }

    public function invite()
    {
        return $this->belongsToMany(Invite::class, 'invite_riskarea_riskfield', 'riskarea_riskfield_id', 'invite_id')
                    ->withPivot(['insert', 'edit', 'view'])
                    ->using(InviteRiskAreaRiskField::class);
    }
}
use Illuminate\Database\Eloquent\Relations\Pivot;

class InviteRiskareaRiskfield extends Pivot
{
    public function invite()
    {
        return $this->belongsTo(Invite::class, 'invite_id');
    }

    public function riskarea_riskfield()
    {
        return $this->belongsTo(RiskAreaRiskField::class, 'riskarea_riskfield_id');
    }
}
$invite = Invite::find(/* some id */);

// sync with riskarea_riskfield id 1, 2 and 3
$invite->riskarea_riskfield() // the belongsToMany relationship
    ->sync([
        1, // default values for insert, edit, view
        2 => ['insert' => 432, 'edit' => 13, 'view' => 542],
        3 => ['insert' => 654, 'edit' => 777, 'view' => 222]
    ]);


// sync with riskarea_riskfield id 4, 5 and 6 with the same permissions
$invite->riskarea_riskfield() // the belongsToMany relationship
    ->syncWithPivotValues(
        [4, 5, 6],
        ['insert' => 654, 'edit' => 777, 'view' => 222]
    );