netzaffin
netzaffin

Reputation: 1632

Laravel Eager Loading: Skip if relation exists

A user may have many votes and many occasions. An occasion can contain some of these votes.

Peter has created three votes. He also has created one occasion with two votes. Peter has five votes at all.


I want to fetch all votes, that are not part of an occasion for performance reasons.

This will load all votes:

$oUser->load( 'votes' );

This is what I've done so far:

$aLoad = array( 'votes' => function($query) {
   $query->whereNotIn('id', json_decode(json_encode(DB::raw('select id from occasions_votes')), true));
});

My Problems

  1. It doesn't work. This still fetches all votes, even if the id exists in the occasion_votes table.
  2. This does not look like it would save performance.

How would you solve it?

Should I do multiple queries (fetch all vote ids > remove all vote ids that exists in occasions_votes > fetch votes of remaining ids) or is there a straight forard way to go? (Laravel 4.2)

Upvotes: 0

Views: 901

Answers (1)

oseintow
oseintow

Reputation: 7391

Try

App\User::with('votes')->whereHas('votes',function($query){
   $query->whereNotIn('id',DB::table('occasions_votes')->get()->lists('id')->all());
})

hope it helps.

Upvotes: 3

Related Questions