Home > Net >  How I can check that unique data in pivot table already exists?
How I can check that unique data in pivot table already exists?

Time:12-02

In laravel 9 I have table pivot table defined :

    Schema::create('article_vote', function (Blueprint $table) {
        $table->id();
        $table->foreignId('article_id')->references('id')->on('articles')->onUpdate('RESTRICT')->onDelete('CASCADE');
        $table->foreignId('vote_id')->references('id')->on('votes')->onUpdate('RESTRICT')->onDelete('CASCADE');
        $table->unique(['vote_id', 'article_id'], 'article_vote_vote_id_article_id_index');
        ...
    });

and having in both models methods with belongsToMany I can refer articles of a vote as : $voteArticles = $vote->articles;

When I want to add some more data I do

$vote->articles()->attach($articleId, $data);

But if in database there are already data with article_id / vote_id I got Duplicate entry error.

In which way I can check that such data in article_vote already exists ?

Thanks!

CodePudding user response:

You can check like this before calling attach.

if (!$vote->articles()->where('article_id', $articleId)->exists()) {
    $vote->articles()->attach($articleId, $data);
}

CodePudding user response:

To check if an entry already exists in a pivot table in Laravel, you can use the wherePivot method on the relationship object. For example, if you have a votes table and an articles table, and a pivot table called article_vote that connects them, you can check if a particular vote and article already have a pivot record like this:

$voteArticles = $vote->articles()->wherePivot('article_id', $articleId)->wherePivot('vote_id', $voteId)->get();
if ($voteArticles->isEmpty()) {
    // The pivot record does not exist, so you can add it here
    $vote->articles()->attach($articleId, $data);
}

The wherePivot method allows you to add additional constraints to the relationship query, in this case checking if the article_id and vote_id columns in the pivot table match the given IDs. If the query returns no results, then you can add the pivot record safely without encountering a duplicate entry error.

CodePudding user response:

Use syncWithoutDetaching instead of attach.

$vote->articles()->syncWithoutDetaching([$articleId => $data]);
  • Related