TheDude's avatar

Eloquent relationships composite primary key

        Schema::create('sentence_word', function (Blueprint $table) {
            $table->integer('word_id')->unsigned()->index();
            $table->foreign('word_id')->references('id')->on('words');
            $table->integer('sentence_id')->unsigned()->index();
            $table->foreign('sentence_id')->references('id')->on('sentences');
            $table->primary(['word_id', 'sentence_id']);
        });

later on...

$sentence->words()->save($word);

in the pivot table (sentence_id), I want each combination to have only one entries, but it is allow multiple entries with exactly the same word sentence pair.

0 likes
4 replies
LaryAI's avatar
Level 58

To ensure that each combination of word and sentence has only one entry in the pivot table, you can use the sync() method instead of save() method. The sync() method will remove any existing entries for the given sentence and then add the new entry. Here's an example:

$sentence->words()->sync([$word->id]);

This will remove any existing entries for the given sentence and then add the new entry for the given word.

TheDude's avatar

@vincent15000 something like this? (its a pivot table, so it doesnt have a model)

        Schema::create('sentence_word', function (Blueprint $table) {
           //$table->primary(['word_id', 'sentence_id']);
            $table->unique(['word_id', 'sentence_id']);
        });
1 like
vincent15000's avatar

@TheDude Yes like this. This will assure that you have a unique (word_id, sentence_id) pair in the table.

Please or to participate in this conversation.