【问题标题】:laravel attach missing id SQL NOT NULL CONSTRAINTlaravel 附加缺少 id SQL NOT NULL CONSTRAINT
【发布时间】:2020-04-06 09:18:47
【问题描述】:

我尝试在 Laravel 中以多对多关系附加 2 个对象。

所以我有用户和团队。当我尝试$user->teams()->attach($team->id, ['instrument_user_id' => $randomInstrument, 'is_leader' => $is_leader]); 时,出现下一个错误:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: team_members.user_id (SQL: insert into "team_members" ("team_id", "instrument_user_id", "is_leader") values (73, 1, 0))

当我尝试$team->members()->attach($user->id, ['instrument_user_id' => $randomInstrument, 'is_leader' => $is_leader]); 时,我得到了下一个错误:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: team_members.team_id (SQL: insert into "team_members" ("user_id", "instrument_user_id", "is_leader") values (1, 1, 0))

那么我必须在哪里添加我要附加的项目的 id,或者我做错了什么?

用户模型:

public function teams(){
        return $this->belongsToMany('App\Team', 'team_members', 'team_id')
                    ->as('details')
                    ->withPivot('instrument_user_id', 'is_leader')
                    ->using('App\TeamMember');
    }

团队模型:

public function members()
    {
        return $this->belongsToMany('\App\User', 'team_members', 'user_id')
                    ->as('details')
                    ->withPivot('instrument_user_id','is_leader')
                    ->using('App\TeamMember');
    }

【问题讨论】:

    标签: php sql laravel eloquent many-to-many


    【解决方案1】:

    尝试这种关系:

    团队模型:

    public function teams(){
            return $this->belongsToMany('App\Team', 'team_members', 'team_id', 'user_id')
                        ->as('details')
                        ->withPivot('instrument_user_id', 'is_leader')
                        ->using('App\TeamMember');
        }
    

    团队模型:

    public function members()
        {
            return $this->belongsToMany('\App\User', 'team_members', 'user_id', 'team_id')
                        ->as('details')
                        ->withPivot('instrument_user_id','is_leader')
                        ->using('App\TeamMember');
        }
    

    【讨论】:

    • 哦,这很简单!谢谢!我找了 3 天,你保存了我的项目!
    猜你喜欢
    • 2022-11-24
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多