eloquenteloquent-relationship

Laravel Eloquent Query Optimization for Pivot Table


I have asked this but this doesn't seems to me the efficient way of querying and even the cost is much more per query or search.

function is_voted($model) {
  return $model->voters->find(auth()->id());
}
function is_voted_up_or_down($model) {
  $is_up = $model->voters()->where('user_id', auth()->id())->where('type', 'up')->exists();
  $is_down = $model->voters()->where('user_id', auth()->id())->where('type', 'down')->exists();
  if($is_up) { //$is_up has a boolean value true or false
    return "up";
  } elseif($is_down) { //$is_down has a boolean value true or false
    return "down";
  } else {
    return "not voted yet";
  }
}

Solution

  • The documetations clear it up. https://laravel.com/docs/11.x/eloquent-relationships.

    The relations seems to be the ManyToMany, not Polymorphic, so just define the functions as per the requirements in models, usually.

    However, if you able to convert this into Polymorphic relation OneToMany, there is a way you could apply something like this

    // Retrieve all posts that have at least one comment...
    $posts = Post::has('comments')->get();
    
    // Retrieve all posts that have three or more comments...
    $posts = Post::has('comments', '>=', 3)->get();