Laravel学习记录--Model

Model类 app/

继承:ILLuminate\Database\Eloquent\Model
model与表名的关系
表名去掉s 就是关于这个表的model类
如users表 的Model类叫 User

创建model
使用命令提示符创建 Model
php artisan make:model ModelName

Model的使用
use model类

  1. new model对象
    model=new App\ModelName

  2. 使用静态方法调用
    App\ModelName::方法名:

简单使用model 添加

$msg = new Msg;
$msg->title='mytitle'
$msg->save();//保存操作

指定连接的数据库

protected $connection ='连接名' 

model 添加多列数据
先在Model类定义保护属性fillable设置允许添加的字段

 protected $fillable = ['name','money','mobile','uid','pubtime'];

数据库添加

Model::create(['表字段名'=>'值','字段名'=>'值'])

简单查询
详情访问laravel查询构造器

$model->where()->first()//单行查询
             ->find(1)//根据主键查询
              ->get()//多行查询
              ->get(['title'])//选择列查询

             ->all()//取出所有数据
             ->all(['title])//选择列查询
            ->where('id','>',1)->select('content')->get();

辅助查询案例,跳过n行取m行

where->skip(n)->take(m)->get();

简单更新,更新前先查询

$flight = App\Flight::find(1);
$flight->name = 'new name';
$flight->save();

批量更新

App\Flight::where('active', 1)
          ->where('name', 'pik')
          ->update(['字段' => '值','字段'=>'值']);
          //active = 1并且;name = pik 的字段更新

批量更新2

$pro = Pro::find($id);//查询当前项目
 $pro->title = request('title');	
        	    $pro->rate = request('rate');
        	    $pro->hrange = request('hrange');
        	    $pro->staus = request('status');
        	    $pro->save();

model删除

$flight = App\Flight::find(1);
$flight->delete();//删除主键id = 1的记录
App\Flight::destroy(1);//删除主键为1的记录
App\Flight::destroy(1, 2, 3);//删除主键为1,2,3的记录

条件删除

$deletedRows = App\Flight::where('active', 0)->delete();//删除actiove = 0的记录

model 约定
model 默认规则表名去掉s就是其model类名
如果不想遵循这种规则需在model类声明属性

protected $table = '表名'//指定操作表

model 默认主键为 id
如果修改默认主键在其类名设置属性

protected $primaryKey = '主键名'//指定主键

laravel默认添加数据库时,会 增加两个字段
create_at ,update_at

如不需要这两个字段,除在迁移文件删除之外
还需在model类设置属性

public $timestamps = false

查询全局作用域
app\Scope

全局范围能为给定模型的所有查询添加约束。Laravel 自带的 软删除功能 就利用全局作用域从数据库中提取「未删除」的模型。编写自定义的全局作用域可以提供一个方便、简单的方法来确保给定模型的每个查询都受到一定的约束。

编写全局作用域
1.定义一个类

namespace App\Scopes;

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

class AgeScope implements Scope
{
    /**
     * 将范围应用于给定的 Eloquent 查询生成器
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        return $builder->where('age', '>', 200);
        //查询限制年龄大于200
    }
}

应用全局作用域

要将全局作用域分配给模型,需要重写给定模型的 boot 方法并使用 addGlobalScope 方法:

<?php

namespace App;

use App\Scopes\AgeScope;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
   
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new AgeScope);
    }
}

匿名的全局作用域

Eloquent 还能使用闭包定义全局作用域,如此一来,便就没必要定义一个单独的类了:

namespace App;

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

class User extends Model
{
   
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('age', function(Builder $builder) {
            $builder->where('age', '>', 200);
        });
    }
}

注:如果你的全局作用域需要添加列到查询的 select 子句,需要使用 addSelect 方法来替代 select,这样就可以避免已存在的
select 查询子句造成影响。

删除全局作用域
删除一个全局作用域

User::withoutGlobalScope(AgeScope::class)->get();

删除多个全局作用域
如果你想要删除几个甚至全部的全局作用域,可以使用 withoutGlobalScopes 方法:

// 删除所有的全局作用域
User::withoutGlobalScopes()->get();

// 删除一些全局作用域
User::withoutGlobalScopes([
    FirstScope::class, SecondScope::class
])->get()

本地作用域
本地作用域定义通用的约束集合方便复用

定义方法 在约束方法前加scope

public function scopeFlag($query){
	return $query->where('flag',1);
	//状态为上架的书
}

调用本地作用域
直接调用scope方法即可,调用时不需加scope前缀
可同时调用多个scope

public function add(){
        $res=Good::Flag()->get();
        dump($res);
    
    }

全局作用域可理解为限制约束,本地作用域则可理解为一些定义好的常用约束集合,使用时直接调用即可。

发布了17 篇原创文章 · 获赞 0 · 访问量 463

猜你喜欢

转载自blog.csdn.net/weixin_45143481/article/details/103936432