侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

在laravel模型中的scope范围查询之查询作用域

Laravel  /  管理员 发布于 4个月前   175

本文简单了解一下laravel Scope的全局范围、本地范围、动态作用域等使用示例代码


全局范围

让我们在app/Scopes/HasActiveScope.php文件中创建一个新的类, 内容如下

<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class HasActiveScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('active', true);
    }
}

你应该覆盖模型的booted方法并调用模型的addGlobalScope方法。

addGlobalScope 方法接受你的作用域的一个实例作为它的唯一参数

<?php
namespace App\Models;
use App\Scopes\HasActiveScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        // using seperate scope class
        static::addGlobalScope(new HasActiveScope);
        // you can do the same thing using anonymous function
        // let's add another scope using anonymous function
        static::addGlobalScope('delete', function (Builder $builder) {
            $builder->where('deleted', false);
        });
    }


使用全局范围

# fetching all active and non-deleted users
$users = User::all();
# above query will result in following sql
select * from `users` where `active` = 1 and `deleted` = 0


从查询中删除范围

你可能不希望你的全局过滤器被应用。例如,如果你想获取所有的用户,无论他们是否处于活动状态。

在这种情况下,你可以用下面的例子删除你应用的范围

# fetch all users weather they are active or not
$users = User::withoutGlobalScope(new HasActiveScope)->all();
# fetch active users weather they are deleted or not
User::withoutGlobalScope('delete')->all();


本地范围

本地作用域是以Scope关键字为前缀的。在这种情况下,你可以在你的Laravel模型中添加本地作用域,而不是定义全局作用域,如下所示

<?php
namespace App\Models;
use App\Scopes\HasActiveScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
    public function scopeDelete($query)
    {
        return $query->where('delete', 0);
    }
}


使用本地范围

# apply active local scope to following query
$users = User::active()->orderBy('created_at')->get();
# apply delete local scope to following query
$users = User::delete()->orderBy('created_at')->get();


动态作用域

有时你可能想给你的局部作用域传递额外的参数。在这种情况下,我们可以向我们的局部作用域传递动态参数,它将作为动态作用域。

<?php
namespace App\Models;
use App\Scopes\HasActiveScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
    public function scopeDelete($query)
    {
        return $query->where('delete', 0);
    }
    public function scopeWithRole($query, $role)
    {
        return $query->where('role', $role);
    }
}


使用动态作用域

# find active users with role admin
$users = User::active()->withRole('admin')->all();


我希望对你有所帮助!


  • 上一条:
    在go语言中将jaeger集成到grpc服务中的流程步骤
    下一条:
    国内又抓获一起非法使用VPN翻墙工具,制售VPN案件
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在Laravel项目中使用中间件方式统计用户在线时长功能代码示例(0个评论)
    • 在Laravel中构建业务流程模型(0个评论)
    • 在Laravel项目中的实现无密码认证之:发送邮箱链接授权(0个评论)
    • Laravel 10.4版本发布(0个评论)
    • 在laravel框架中的5个HTTP客户端技巧分享(0个评论)
    • 近期文章
    • 如何优雅处理async await错误推荐:await-to-js库(0个评论)
    • lodash工具库(0个评论)
    • 在Laravel项目中使用中间件方式统计用户在线时长功能代码示例(0个评论)
    • 在Laravel中构建业务流程模型(0个评论)
    • windows系统中安装FFMpeg及在phpstudy环境php7.3 + php-ffmpeg扩展的使用流程步骤(0个评论)
    • 在go语言中对浮点的数组、切片(slice)进行正向排序和反向排序(0个评论)
    • 在go语言中对整数数组、切片(slice)进行排序和反向排序(0个评论)
    • 在go语言中对字符串数组、切片(slice)进行排序和反向排序(0个评论)
    • 最新国内免注册ChatGPT体验站_ChatGPT镜像站访问链接地址2023/3/28持续更新(0个评论)
    • 在Laravel项目中的实现无密码认证之:发送邮箱链接授权(0个评论)
    • 近期评论
    • 博主 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..
    • xiaoB 在

      2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..
    • BUG4 在

      你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..
    • 博主 在

      go语言+beego框架中获取get,post请求的所有参数中评论 @ t1  直接在router.go文件中配就ok..
    • Jade 在

      如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-01
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客