Created
November 29, 2018 23:01
-
-
Save adamcrampton/7573856b245b21a7b5bc479b85e046a3 to your computer and use it in GitHub Desktop.
Laravel Eloquent whereHas query example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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