Home > Software design >  How to get 1 row in pivot table?
How to get 1 row in pivot table?

Time:11-28

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');
    ...
});

and having in both models methods with belongsToMany I can refer articles of a vote as :

$voteArticles = $vote->articles;

I got all related articles, but how can O get only 1 row if I have $articleId ?

Thanks!

CodePudding user response:

That can be achieved in a number of ways by querying the relations:

$vote->articles()->where('id', $articleId)->first();

$vote->articles()->whereKey($articleId)->first();

$vote->articles()->find($articleId);

$vote->articles()->findOrFail($articleId);

Or in your example, you already have a collection of articles. We can also do this:

$vote->articles->find($articleId);

$vote->articles->findOrFail($articleId);
  • Related