Skip to content

Instantly share code, notes, and snippets.

@adamcrampton
Created November 29, 2018 23:01
Show Gist options
  • Save adamcrampton/7573856b245b21a7b5bc479b85e046a3 to your computer and use it in GitHub Desktop.
Save adamcrampton/7573856b245b21a7b5bc479b85e046a3 to your computer and use it in GitHub Desktop.
Laravel Eloquent whereHas query example
class TaxonomyEntity extends Model
{
/**
* Get a list of categories with optional limit and order parameters.
* @param integer $limit
* @param string $order
* @return @return\Illuminate\Database\Eloquent\Collection
*/
public function getCategories($limit = 5, $order = 'DESC')
{
$categories = TaxonomyEntity::whereHas('taxonomy_types', function($query) {
$query->where('taxonomy_type_name', 'category');
})->take($limit)
->get();
}
/**
* Get taxonomy type for this taxonomy entity.
* @return\Illuminate\Database\Eloquent\Collection
*/
public function taxonomy_types()
{
return $this->hasMany('App\Models\TaxonomyType', 'id', 'taxonomy_types_fk');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment