乐趣区

关于php:Laravel-Eloquent-ORM-的本地作用域

定义:

class User extends Model
{public function scopePopular($query)
    {return $query->where('votes', '>', 100);
    }

    public function scopeActive($query)
    {return $query->where('active', 1);
    }
    
    public function scopeOfType($query, $type)
    {return $query->where('type', $type);
    }
}

应用:

$users = App\User::popular()->active()->ofType('admin')->orderBy('created_at')->get();

$users = App\User::popular()->orWhere(function (Builder $query) {$query->active();
})->get();
# 或者
$users = App\User::popular()->orWhere->active()->get();
退出移动版