建立/建立多对多关系

时间:2019-05-23 13:47:03

标签: php laravel

我有两个模特获胜者和竞赛者,一个获胜者可能赢得了很多比赛,并且一场竞赛可能已经被许多获胜者赢得了,这对我来说是多对多的关系。

现在,我创建了两个迁移和数据透视表迁移:

Schema::create('winners', function (Blueprint $table) {
            $table->increments('id'); 
            $table->string('instagram');
            $table->timestamps();
        });

Schema::create('competitions', function (Blueprint $table) {
            $table->increments('id'); 
            $table->string('name');
            $table->timestamps();
        });

Schema::create('winner_competition', function (Blueprint $table) {
            $table->integer('winner_id')->unsigned();
            $table->integer('competition_id')->unsigned();
            $table->foreign('winner_id')->references('id')->on('winners')->onDelete('cascade')->onUpdate('cascade');
            $table->foreign('competition_id')->references('id')->on('competitions')->onDelete('cascade')->onUpdate('cascade');
        });

现在我想通过种子创建一些获胜者,但我不知道该如何在种子文件和控制器方法中为获胜者分配比赛:

public function create(Create $request)
    {
        $winner = new Winner();
        $winner->instagram = $request->input('instagram');
        $winner->competition_id = '?';
        $winner->save();

        return response()->json([
            'winner' => $winner
        ]);
    }

DB::table('winners')->insert([
            'instagram' => '@hfgfgdhdd',
            'competition_id' => '?'
        ]);

有人对我有所启发。

1 个答案:

答案 0 :(得分:0)

到目前为止,由于您与多对多关系:

$winner = new Winner();
$winner->instagram = $request->input('instagram');
$winner->save(); //add record in the DB
$competition = Competition::where(/**/); // <- you have to query certain competition here
$competition->winners()->attach($winner->id); //add record in the pivot table without check if such winner_id-competition_id pair exists

Reference

您的模型必须定义relationship

//Winner model
public function competitions()
{
    return $this->belongsToMany(Competition::class);
    //you can pass table name as 2nd parameter:
    //return $this->belongsToMany(Competition::class, 'winner_competition');
}

//Competition model
public function winners()
{
    return $this->belongsToMany(Winner::class);
}

P。 S.创建新的获胜者可以更加简单:

$winner = Winner::create(['instagram' => $request->input('instagram')]);
$competition = Competition::where(/**/);
$competition->winners()->attach($winner->id);