Laravel-查询作用域

Laravel-查询作用域

标签(空格分隔): php, laravel

全局作用域

## 编写全局作用域 ##

编写全局作用域很简单。定义一个实现 Illuminate\Database\Eloquent\Scope 接口的类,并实现 apply 这个方法。 根据你的需求,在 apply 方法中加入查询的 where 条件:

<?php
namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class OrderStatusScopes implements Scope
{
    /**
     * 把约束加到 Eloquent 查询构造中。
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('status', '=', 2);
    }
}

## 在模型中应用全局作用域 ##



/**
 *  模型的 「启动」 方法.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    //对象添加
    static::addGlobalScope(new OrderStatusScopes());

    // 匿名添加 [全局作用域]
    static::addGlobalScope('platform', function (Builder $builder){
        $builder->where('platform', '=', 2);
    });
}

## 移除全局作用域 ##



移除类名方式
OrderModel::withoutGlobalScope(OrderStatusScopes::class)->get();

移除全部
OrderModel::withoutGlobalScopes()->get();

移除部分
User::withoutGlobalScopes([
FirstScope::class, SecondScope::class
])->get();

本地作用域

## 在模型中编写本地作用域 ##



只需要在对应的 Eloquent 模型方法前添加 scope 前缀

/**
 * 本地作用域 [scope + youActionName]
 *
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeProgram($query)
{
    return $query->where('platform', 1);
}


/**
 * 在模型中编写本地动态作用域 [scope + youActionName]
 *
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeStatus($query, $type)
{
    return $query->where('status', $type);
}


## 应用本地作用域 ##



OrderModel::Program()->Status(1)->get();

转载于:https://www.cnblogs.com/yanweifeng/p/10956877.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值