J
J
jazzus2018-12-27 09:55:57
Laravel
jazzus, 2018-12-27 09:55:57

Is it possible to exclude find for WithCount?

I check the quantity through withcount. Made in the model

public function hasModel($model)
  {
    if ($this->withCount($model)->find($this->id)->{$model.'_count'}>0) return true;
    return false;
  }

And I feel that you can do without find($this->id). We after all already address to the found object. But without find there is an error.
You can make it easier with a count:
public function hasModel($model)
    {
      if ($this->$model()->count()>0) return true;
      return false;
    }

but as far as I know from the documentation withcount is a more optimized way to count the number. Or is there no difference in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kovalchuk, 2018-12-27
@jazzus

It is necessary to call not the model, but the relation function

public function hasModel($relation)
{
  return $this->$relation()->count()>0;
}
public function comments()
{
    return $this->hasMany('App\Comment');
}
...
$this->hasModel('comments')

but in general it is better to use has
public function comments()
{
    return $this->hasMany('App\Comment');
}
...
$this->has('comments')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question