For Eloquent models one may create custom query scopes like this:
class User extends Model
{
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
And then one may call it like this:
User::popular()->get();
I would like to use such scope functions for a queries that I use with the database query builder of Laravel. Something like
\DB::table('users')->popular()->get();
I have to use the database query builder, because I query for a large result set and converting them into Eloquent models takes too long.
It is possible to define query scopes for the Laravel database query builder?
Remarks
-
In the answer of https://stackoverflow.com/a/28420807/2311074 a solution is proposed where one has to create a extra class, so something like
\DB::table('users')->popular()->get();
would not work. -
I also tried something like
class MyCustomDB extends DB { public function popular($query) { // ... } }
But
MyCustomDB::table('users')->popular()->get();
failed with
BadMethodCallException: Method Illuminate\Database\Query\Builder::popular does not exist.
-
In How to customize Laravel's Database\Query\Builder (make better subquery) a solution is proposed how to customize the query builder for Eloquent models. But not how to customize the query builder for the database.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire