博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
20个Laravel Eloquent 使用技巧
阅读量:6243 次
发布时间:2019-06-22

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

转载自

1、自增、自减

//常规写法    $article = Article::find($article_id);    $article->read_count++;    $article->save();        //eloquent写法-1    $article = Article::find($article_id);    $article->increment('read_count');        //eloquent写法-2 链式写法    Article::find($article_id)->increment('read_count');    Article::find($article_id)->increment('read_count', 10); // +10    Product::find($produce_id)->decrement('stock'); // -1复制代码

2、条件式方法 XorY methods

  • findOrFail(): 查询不到的时候直接报错
$user = User::find($id);    if (!$user) { abort (404); }    //以上代码等同于    $user = User::findOrFail($id);复制代码
  • firstOrCreate():使用给定的字段及其值在数据库中查找记录。如果在数据库中找不到模型,则将使用第一个参数中的属性以及可选的第二个参数中的属性插入记录
// 通过 name 属性检索航班,当结果不存在时创建它...    $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);    // 通过 name 属性检索航班,当结果不存在的时候用 name 属性和 delayed 属性去创建它    $flight = App\Flight::firstOrCreate(        ['name' => 'Flight 10'], ['delayed' => 1]    );复制代码
  • firstOrNew():用法和firstOrCreate()一样,但是firstOrNew()只是实例化一个对象,如果需要持久化则需要save()保存
  • updateOrCreate(): 更新现有模型或创建新模型(如果不存在),同firstOrCreate()

3、Modelboot()方法

/**     * 基类:新增的时候自动将`uuid`字段用`Uuid`生成器填充     */    class BaseModel extends Model    {        public static function boot()        {            parent::boot();            self::creating(function ($model) {                $model->uuid = (string)Uuid::generate();            });        }    }        /**     * 用户模型:修改的时候设置额外的操作     */    class User extends BaseModel    {        public static function boot()        {            parent::boot();            static::updating(function($model)            {                // do some logging                // override some property like $model->something = transform($something);            });        }    }复制代码

4、关联添加额外条件并设置排序Relationship with conditions and ordering

//通常的做法,关联用户模型    public function users() {        return $this->hasMany('App\User');        }    //关联已经批准并用`email`排序的用户模型    public function approvedUsers() {        return $this->hasMany('App\User')->where('approved', 1)->orderBy('email');    }复制代码

5、Model类属性 Model properties: timestamps, appends etc.

class User extends Model {        //经常用到的属性        protected $table = 'users';        protected $fillable = ['email', 'password']; // which fields can be filled with User::create()        protected $dates = ['created_at', 'deleted_at']; // which fields will be Carbon-ized        protected $appends = ['field1', 'field2']; // additional values returned in JSON                //其他很有用的属性        protected $primaryKey = 'uuid'; // it doesn't have to be "id"        protected $keyType = 'string'; //设置主键字段类型 default `int`        public $incrementing = false; // and it doesn't even have to be auto-incrementing!        protected $perPage = 25; // Yes, you can override pagination count PER MODEL (default 15)        const CREATED_AT = 'created_at';        const UPDATED_AT = 'updated_at'; // Yes, even those names can be overridden        public $timestamps = false; // or even not used at all    }复制代码

6、用find方法查找多条记录Find multiple entries

//find常用用法    $user = User::find(1);    //find其实也接收 数组 为参数    $users = User::find([1,2,3]);复制代码

7、whereX魔术方法

//where字段名:字段名第一字母大写    $users = User::whereApproved(1)->get(); //等同于 $users = User::where('approved', 1)->get();    User::whereDate('created_at', date('Y-m-d'));    User::whereDay('created_at', date('d'));    User::whereMonth('created_at', date('m'));    User::whereYear('created_at', date('Y'));复制代码

8、Order by relationship

场景:论坛很多帖子topic,需要按有最新发言post的来排序

//帖子关联最新的发言    public function latestPost()    {        return $this->hasOne(\App\Post::class)->latest();    }    $users = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');复制代码

9、Eloquent::when()别再写那么多的if-else

//通常的写法    if (request('filter_by') == 'likes') {        $query->where('likes', '>', request('likes_amount', 0));    }    if (request('filter_by') == 'date') {        $query->orderBy('created_at', request('ordering_rule', 'desc'));    }        //Eloquent::when()写法    $query = Author::query();    $query->when(request('filter_by') == 'likes', function ($q) {        return $q->where('likes', '>', request('likes_amount', 0));    });    $query->when(request('filter_by') == 'date', function ($q) {        return $q->orderBy('created_at', request('ordering_rule', 'desc'));    });    //可以传递参数    $query = User::query();    $query->when(request('role', false), function ($q, $role) {         return $q->where('role_id', $role);    });    $authors = $query->get();复制代码

10、BelongsTo Default Models

//blade:如果 author 被删了就会报错    {
{ $post->author->name }} //设置 缺省Model 避免以上错误 public function author() { return $this->belongsTo('App\Author')->withDefault([ 'name' => 'Guest Author' ]); }复制代码

11、Order by Mutator : 借助集合collect->sortBy方法

function getFullNameAttribute()    {      return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];    }    //错误写法    $clients = Client::orderBy('full_name')->get(); // doesn't work    //正确写法,借助collect的sortBy方法    $clients = Client::get()->sortBy('full_name'); // works!复制代码

12、Default ordering in global scope

protected static function boot()    {        parent::boot();            // Order by name ASC        static::addGlobalScope('order', function (Builder $builder) {            $builder->orderBy('name', 'asc');        });    }复制代码

13、 Raw query methods

// whereRaw    $orders = DB::table('orders')        ->whereRaw('price > IF(state = "TX", ?, 100)', [200])        ->get();        // havingRaw    Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get();        // orderByRaw    User::where('created_at', '>', '2016-01-01')      ->orderByRaw('(updated_at - created_at) desc')      ->get();复制代码

14、Replicate: make a copy of a row

这是复制某条记录最好的方法

$task = Tasks::find(1);    $newTask = $task->replicate();    $newTask->save();复制代码

15、Chunk() method for big tables

Collect集合方法:需要输出大量记录的时候用chunk

User::chunk(100, function ($users) {        foreach ($users as $user) {            // ...        }    });复制代码

16、Create additional things when creating a model

artisan命令生成model的时候一起生成controller -rmigration file

php artisan make:model Company -mcr复制代码

17、Override updated_at when saving

save()方法接收额外的参数

$product = Product::find($id);    $product->updated_at = '2019-01-01 10:00:00';    $product->save(['timestamps' => false]);复制代码

18、What is the result of an update()?

//返回更新的记录数    $result = $products->whereNull('category_id')->update(['category_id' => 2]);复制代码

19、where参数分组

//... WHERE (gender = 'Male' and age >= 18) or (gender = 'Female' and age >= 65) 的 Eloquent 写法    $q->where(function ($query) {        $query->where('gender', 'Male')            ->where('age', '>=', 18);    })->orWhere(function($query) {        $query->where('gender', 'Female')            ->where('age', '>=', 65);     })复制代码

20、orWhere with multiple parameters

$q->orWhere(['b' => 2, 'c' => 3]);复制代码
你可能感兴趣的文章
JSP实现用户登录样例
查看>>
搞笑的W3C和M$对DOM中属性命名
查看>>
[Struts]让Dreamweaver显示Struts标签的插件
查看>>
便利的html5 之 required、number 、pattern
查看>>
[LeetCode] Find K Pairs with Smallest Sums 找和最小的K对数字
查看>>
VC6.0 C++ 如何调用微软windows系统SDK 语音API
查看>>
Python 3.5 RuntimeError: can't start new thread
查看>>
POJ 1659 Frogs' Neighborhood(可图性判定—Havel-Hakimi定理)【超详解】
查看>>
数字统计问题
查看>>
Windows下Redis缓存服务器的使用 .NET StackExchange.Redis Redis Desktop Manager
查看>>
SharpMap简析
查看>>
使用类加载器加载配置文件/getClassLoader().getResourceAsStream()
查看>>
配置 linux-bridge mechanism driver - 每天5分钟玩转 OpenStack(77)
查看>>
matplotlib绑定到PyQt5(有菜单)
查看>>
iOS - QRCode 二维码
查看>>
记录第一次纯手打爬虫经历
查看>>
PyCharm 开发Django ,错误汇总
查看>>
插入排序
查看>>
一个完整的C++程序SpreadSheet - 1) 类的声明和定义
查看>>
iOS6.1爆严重安全漏洞 解锁不用密码
查看>>