Adis Azhar
Adis Azhar

Reputation: 1022

Laravel Querying Relationship Existence

I have the following query in my Laravel controller:

public function getTeams(){      
  $teams = Team::whereHas('submissions', function($q){
    $q->limit(1);
  })->with(['submissions'])->get();

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

Team model:

   public function submissions(){
        return $this->hasMany('App\submission', 'team_id', 'id');
    }

Submission model:

public function team(){
    return $this->belongsTo('App\Team', 'id', 'team_id');
}

Now I am trying to get only one submission in getTeams method. But the limit function isn't working correctly. It doesn't return any errors. It returns all submissions for each team. I only want 1 submission. How do I make it work?

enter image description here

Upvotes: 1

Views: 738

Answers (2)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

There is no simple way to limit eager loading.

You can use a HasOne relationship:

public function submission() {
    return $this->hasOne('App\submission', 'team_id', 'id');
}

$teams = Team::has('submission')->with('submission')->get();

This will still fetch all submissions in the background, but only show one for each $team.

BTW: You could improve the query by removing has('submission') and filtering the teams afterwards.

$teams = Team::with('submission')->get();
$teams = $teams->where('submission', '!==', null)

Upvotes: 1

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

 $teams = Team::whereHas('submissions')
    ->with([
        'submissions' => function($query) {
            $query->limit(1);
        }
    ])->get();

Upvotes: 1

Related Questions