欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

queryScope 和 setAttribute 用法

程序员文章站 2022-05-31 17:25:32
...

setAttribute

在表单中创建日期,然后直接处理,而不用在controller里面写时间原来的在controller里面写时间

app/Http/Controllers/ArticlesController.php    public function store(Request $requests){        $input = Request::$requests->all();        $input['publish_at']=Carbon::now();  //原来这里是通过直接硬性写时间进去        Articles::create($input);        return redirect('/articles');    }

改为在表单中处理时间

app/Http/Controllers/ArticlesController.php    public function store(Request $requests){ //现在取消掉硬性写时间        Articles::create($requests->all());        return redirect('/articles');    }

(表单)

resources/views/articles/create.blade.php@extends('layout.app')@section('content')    

创建文章

{!! Form::open(['url'=>'/articles/store']) !!}
{!! Form::label('title', 'Title:') !!} {!! Form::text('title', null, ['class' => 'form-control']) !!}
{!! Form::label('content', 'Content:') !!} {!! Form::textarea('content', null, ['class' => 'form-control']) !!}
{!! Form::label('publish_at', 'publish_at:') !!} {!! Form::date('publish_at', date('Y-m-d'), ['class' => 'form-control']) !!} //这里写时间,由用户选择输入
{!! Form::submit('发表文章',['class'=>'btn btn-primary form-control']) !!} {!! Form::close() !!}@stop

在数据库里显示的情况

id  title   content publish_at  created_at  updated_at5   我是一篇新文章 你好  2016-05-21 00:00:00 2016-05-21 07:32:48 2016-05-21 07:32:48 //这里的时间只有日期,而没有时分

所以,引申出一个解决办法,在model里面写方法,通过model跟数据库的关联,从而在写入数据库的时候进行时间格式转换(同理可鉴其他数据的处理)

这就是setAttribute 用法

在model里面写,写一个自动处理的function setattribute

app/Articles.phpclass Articles extends Model{    protected $fillable=['title','content','publish_at'];    public function setPublishAtAttribute($date)    //set + 字段名  + attribute 组成的,laravel会自动判断字段名,并且名字要遵循驼峰命名法    {        $this->attributes['publish_at'] = Carbon::createFromFormat('Y-m-d',$date); //调用model的attributes方法来设置    }}

数据库可以看到数据已经生成,并且时间有时分。

id  title   content publish_at  created_at  updated_at6   我是第二篇文章 爱的飒飒大   2016-05-27 08:17:29 2016-05-21 08:17:29 2016-05-21 08:17:29

原来的setattribute是叫setattribute的,不过也支持这样中间插入一个字段,在debug的过程中也可以看到他的转换过程

in Carbon.php line 425at Carbon::createFromFormat('Y-n-j G:i:s', 'Y-m-d-2016-05-27-21 8:21:00', null) in Carbon.php line 368at Carbon::create('Y-m-d', '2016-05-27', null, null, null, null, null) in Carbon.php line 383at Carbon::createFromDate('Y-m-d', '2016-05-27') in Articles.php line 14 at Articles->setPublishAtAttribute('2016-05-27') in Model.php line 2860  //这里调用setPublishAtAttributeat Model->setAttribute('publish_at', '2016-05-27') in Model.php line 447 //这里就转变成setAttributeat Model->fill(array('_token' => '', 'title' => '我是第二篇文章', 'content' => '爱的飒飒大', 'publish_at' => '2016-05-27')) in Model.php line 281at Model->__construct(array('_token' => '', 'title' => '我是第二篇文章', 'content' => '爱的飒飒大', 'publish_at' => '2016-05-27')) in Model.php line 569at Model::create(array('_token' => '', 'title' => '我是第二篇文章', 'content' => '爱的飒飒大', 'publish_at' => '2016-05-27')) in ArticlesController.php line 31at ArticlesController->store(object(Request))

queryscope

将原来的硬性写在controller的处理时间的方法进行修改

app/Http/Controllers/ArticlesController.php    public function index(){        $articles = Articles::latest()->where('publish_at','>=',Carbon::now())->get(); //这里通过直接写时间处理方法来实现数据处理        return view('articles.index',compact('articles'));    }

改为:

    public function index(){//        $articles = Articles::latest()->where('publish_at','get();                $articles = Articles::latest()->publish()->get();                 //创造一个新的方法,目的是更灵活也让目前的代码更加简洁和容易理解,                //例如这里就是从articles里获取大概是最后一条数据然后过滤publish时间然后获取最终数据的大概意思,不用再看where什么的了        return view('articles.index',compact('articles'));    }

然后在model articles里面添加scope

app/Articles.php    public function scopePublish($query){  //scope语法限制,scope+刚才的publish函数名字(需要驼峰法命名)        $query->where('publish_at','    

因为是使用的是model articles的实例,scope命名会让laravel会执行一些自动数据查询,所以能够将数据查询结果$query传入,并且处理

科普知识:

latest()返回的是一个builder对象

Builder|Builder latest(string $column = 'created_at')Add an "order by" clause for a timestamp to the query.Parametersstring  $column Return ValueBuilder|Builder

builder对象是一个特殊的数据对象,是laravel的数据库管理的一个对象,一个builder里面包含了很多数据信息,方便直接使用。

alls方法返回的是一个collection对象

static Collection|Model[] all(array|mixed $columns = array('*'))Get all of the models from the database.Parametersarray|mixed $columns    Return ValueCollection|Model[]

这是collection的格式:

Collection {#136 ▼  #items: array:6 [▼    0 => Articles {#137 ▼      #fillable: array:3 [▶]      #connection: null      #table: null      #primaryKey: "id"      #perPage: 15      +incrementing: true      +timestamps: true      #attributes: array:6 [▼        "id" => 6        "title" => "我是第二篇文章"        "content" => "爱的飒飒大"        "publish_at" => "2016-05-27 08:17:29"        "created_at" => "2016-05-21 08:17:29"  //collection里面的数据是数组包含对象,所以方便调用。        "updated_at" => "2016-05-21 08:17:29"      ]      #original: array:6 [▶]      #relations: []      #hidden: []      #visible: []      #appends: []      #guarded: array:1 [▶]      #dates: []      #dateFormat: null      #casts: []      #touches: []      #observables: []      #with: []      #morphClass: null      +exists: true      +wasRecentlyCreated: false    }    1 => Articles {#138 ▶}    2 => Articles {#139 ▶}    3 => Articles {#140 ▶}    4 => Articles {#141 ▶}    5 => Articles {#142 ▶}  ]}

这是builder的格式:

Builder {#128 ▼  #query: Builder {#127 ▼    #connection: MySqlConnection {#123 ▶}    #grammar: MySqlGrammar {#124 ▶}    #processor: MySqlProcessor {#125}    #bindings: array:6 [▶]    +aggregate: null    +columns: null    +distinct: false    +from: "articles"    +joins: null    +wheres: array:1 [▼ //builder里面包含的数据会存在这里,不过不能直接使用,需要使用像get这样的方法来转换数据。      0 => array:5 [▼        "type" => "Basic"        "column" => "publish_at"        "operator" => ">="        "value" => Carbon {#129 ▼          +"date": "2016-05-21 09:08:10.000000"          +"timezone_type": 3          +"timezone": "UTC"        }        "boolean" => "and"      ]    ]    +groups: null    +havings: null    +orders: array:1 [▶]    +limit: null    +offset: null    +unions: null    +unionLimit: null    +unionOffset: null    +unionOrders: null    +lock: null    #backups: []    #bindingBackups: []    #operators: array:26 [▶]    #useWritePdo: false  }  #model: Articles {#121 ▼    #fillable: array:3 [▶]    #connection: null    #table: null    #primaryKey: "id"    #perPage: 15    +incrementing: true    +timestamps: true    #attributes: []    #original: []    #relations: []    #hidden: []    #visible: []    #appends: []    #guarded: array:1 [▶]    #dates: []    #dateFormat: null    #casts: []    #touches: []    #observables: []    #with: []    #morphClass: null    +exists: false    +wasRecentlyCreated: false  }  #eagerLoad: []  #macros: []  #onDelete: null  #passthru: array:11 [▶]  #scopes: []}