search
HomeBackend DevelopmentPHP TutorialqueryScope 和 setAttribute 用法

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')    <h1 id="创建文章">创建文章</h1>    {!! Form::open(['url'=>'/articles/store']) !!}            <!--- Title Field --->    <div class="form-group">        {!! Form::label('title', 'Title:') !!}        {!! Form::text('title', null, ['class' => 'form-control']) !!}    </div>    <!--- Content Field --->    <div class="form-group">        {!! Form::label('content', 'Content:') !!}        {!! Form::textarea('content', null, ['class' => 'form-control']) !!}    </div>    <!---  Field --->    <div class="form-group">        {!! Form::label('publish_at', 'publish_at:') !!}        {!! Form::date('publish_at', date('Y-m-d'), ['class' => 'form-control']) !!}  //这里写时间,由用户选择输入    </div>    {!! 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','< =',Carbon::now())->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','< =',Carbon::now());  //固定是传入一个$query,暂时的理解是一个数据查询结果,然后使用where过滤数据    }

因为是使用的是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: []}
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!