laravel 学习(20) 模型的作用域
发布日期:2021-06-28 19:45:49 浏览次数:2 分类:技术文章

本文共 1212 字,大约阅读时间需要 4 分钟。

局部操作

查询user表里 性别男 分数 大于50

select * from user where sex = '男' and 'score' >50//模型写法 User::where('sex','男')->where('score','>',90)->get();

可以将男这个片段分装成单独方法,然后统一在模型下调用

首先定义模型namespace App\Model\Source;use Illuminate\Database\Eloquent\Model;class User extends Model{    public function scopeSexMale($query){        return $query->where('sex','男');    }    public function scopeSexWeman($query){        return $query->where('sex','女');    }}

控制器调用

public function list(){        User::sexMale()->get();    }

带参数

#模型 public function scopeSex($query,$val){        return $query->where('sex',$val);    }

控制器

User::sex('女')->get();

全局操作

sql查询必有的条件 

有两种方法

① 建立全局

namespace App\Scopes;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Scope;class StatusScopes implements Scope{    public function apply(Builder $builder, Model $model)    {        // TODO: Implement apply() method.        $builder->where('status',1);    }}

在User模型

//启动全局作用域    protected static function booted()    {        parent::booted(); // TODO: Change the autogenerated stub        static::addGlobalScope(new StatusScopes());    }

控制器调用

User::get();User::toSql(); //打印sql语句

  

②可以使用闭包方法

取消全局

 

 

 

 

 

转载地址:https://blog.csdn.net/xxpxxpoo8/article/details/106856980 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:laravel 学习(21) 访问器,修改器
下一篇:laravel7 学习(19)批量删除,软删除

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月09日 22时05分16秒