Queryscope and SetAttribute usage

Source: Internet
Author: User
Tags dateformat

SetAttribute

Create a date in the form and process it directly without having to write time in the controller to write time in the controller

app/http/controllers/articlescontroller.php Public    function Store (Request $requests) {        $input = request::$ Requests->all ();        $input [' Publish_at ']=carbon::now ();  Originally here is through the direct hard write time to go into        articles::create ($input);        Return redirect ('/articles ');    }

To process time in a form instead

app/http/controllers/articlescontroller.php Public    function Store (Request $requests) {//Cancel hard write time        now Articles::create ($requests->all ());        Return redirect ('/articles ');    }

(form)

Resources/views/articles/create.blade.php@extends (' Layout.app ') @section (' content ')    

Create an article

{!! 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::d ate (' publish_at ', date (' y-m-d '), [' class ' = ' Form-control ']) ! Write the time here, the user selected input {!! Form::submit (' published article ', [' class ' = ' btn btn-primary form-control ']) ! {!! Form::close ()!!} @stop

What is displayed in the database

ID  title   content publish_at  created_at  updated_at5   I'm a new article Hello  2016-05-21 00:00:00 2016-05-21 07:32:48 2016-05-21 07:32:48//The time here is only the date, and no cent

Therefore, a solution is derived, in the model of writing methods, through the model with the database association, so that when writing to the database time format conversion (the same can be used to authenticate other data processing)

This is setattribute usage.

Write in the model, write a function that automatically handles setattribute

App/articles.phpclass articles extends model{    protected $fillable =[' title ', ' content ', ' publish_at '];    Public Function Setpublishatattribute ($date)    //set + field name  + attribute, Laravel will automatically determine the field name, and the name to follow the hump naming method    {        $this->attributes[' publish_at '] = Carbon::createfromformat (' y-m-d ', $date);//Call the model's attributes method to set    }}

The database can see that the data has been generated and time is sometimes divided.

ID  title   content publish_at  created_at  updated_at6   I was the second article love the whispering big   2016-05-27 08:17:29 2016-05-21 08:17:29 2016-05-21 08:17:29

The original setattribute is called setattribute, but also supports the insertion of a field in the middle, during the debug process can also see his conversion process

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 3 68at 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 @ articles->setpublishatattribute (' 2016-05-27 ') in model.php line 2860 Here call Setpublishatattributeat model->setattribute (' publish_at ', ' 2016-05-27 ') in the model.php line 447// Here it turns into setattributeat model->fill (' _token ' + ', ' title ' = ' I'm the second article ', ' content ' = ' Love's whispering Big ', ' Publish_ At ' = ' + ' 2016-05-27 ')) in model.php line 281at model->__construct (' _token ' + ', ' title ' = ' I am the second article ', ' Content ' = ' + ' love of the Whispering Big ', ' publish_at ' = ' 2016-05-27 ')) in the model.php line 569at model::create (Array (' _token ' = ', ' Title ' = ' I am the second article ', ' content ' = ' The Whispering of Love ', ' publish_at ' and ' 2016-05-27 ') in articlescontroller.php line 31at Art Iclescontroller->store (Object (Request))

Queryscope

Modify the original hard-written method in the controller's processing time

app/http/controllers/articlescontroller.php Public    Function Index () {        $articles = Articles::latest () Where (' Publish_at ', ' >= ', Carbon::now ())->get (); This is done by the direct write time processing method to realize the data processing        return view (' Articles.index ', compact (' articles '));    }

Switch

    Public Function Index () {//        $articles = Articles::latest ()->where (' Publish_at ', ' < = ', Carbon::now ()) Get ();                $articles = Articles::latest ()->publish ()->get ();                 Create a new approach that is more flexible and makes the current code more concise and easy to understand,                //For example, here is the approximate meaning of getting the last data from the articles and then filtering the publish time and then getting the final data, without seeing where or what.        return view (' Articles.index ', compact (' articles '));    }

Then add scope to model articles

app/articles.php Public    function Scopepublish ($query) {  //scope syntax restriction, scope+ just publish function name (need hump method named)        $ Query->where (' Publish_at ', ' < = ', Carbon::now ());  The fix is to pass in a $query, the temporary understanding is a data query result, then uses where to filter the data    }

Because it is an instance of model articles, scope naming allows Laravel to perform some automated data queries, so that data query results are $query passed in and processed

Scientific knowledge:

Latest () returns a builder object

builder| Builder Latest (String $column = ' created_at ') Add an "ORDER BY" clause for a timestamp to the query. Parametersstring  $column Return valuebuilder| Builder

The Builder object is a special data object, which is an object of Laravel database management, and a builder contains a lot of data information, which is easy to use directly.

The Alls method returns a collection object

Static collection| Model[] All (array|mixed $columns = Array (' * ')) Get all of the models from the database. parametersarray|mixed $columns    Return valuecollection| Model[]

This is the format of the collection:

Collection {#136 #items: array:6 [0 + articles {#137 #fillable: array:3 [] #connection: null #table: null #primaryKey: "id" #perPage: +incrementing:true +timestamps:true #attributes: AR Ray:6 ["id" + 6 "title" + "I am the second article" "Content" = "love of the Whispering Big" "Publish_at" and "2016"        -05-27 08:17:29 "" created_at "=" 2016-05-21 08:17:29 "//collection The data inside the array contains the object, so it is convenient to call. "Updated_at" = "2016-05-21 08:17:29"] #original: Array:6 [] #relations: [] #hidden: [] #visi BLE: [] #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 = Ar ticles {#142}]}

This is the builder format:

Builder {#128 #query: Builder {#127 #connection: mysqlconnection {#123} #grammar: Mysqlgrammar {#124} #pro  cessor:mysqlprocessor {#125} #bindings: Array:6 [] +aggregate:null +columns:null +distinct:false +from:      The "articles" +joins:null +wheres:array:1 [//builder contains data that exists here, but cannot be used directly and requires a method like get to transform the data. 0 = array:5 ["Type" = "Basic" "column" = "publish_at" "operator" = ">=" " Value "= = Carbon {#129 +" date ":" 2016-05-21 09:08:10.000000 "+" Timezone_type ": 3 +" Timezon E ":" UTC "}" boolean "=" and "]] +groups:null +havings:null +orders:array:1 [] + Limit:null +offset:null +unions:null +unionlimit:null +unionoffset:null +unionorders:null +lock:n    ull #backups: [] #bindingBackups: [] #operators: array:26 [] #useWritePdo: false} #model: articles {#121 #fillable: Array:3 [] #connection: null #table: null #primaryKey: "id" #perPage: +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: []}
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.