搜索
首页后端开发php教程queryScope 和 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: []}
声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP的当前状态:查看网络开发趋势PHP的当前状态:查看网络开发趋势Apr 13, 2025 am 12:20 AM

PHP在现代Web开发中仍然重要,尤其在内容管理和电子商务平台。1)PHP拥有丰富的生态系统和强大框架支持,如Laravel和Symfony。2)性能优化可通过OPcache和Nginx实现。3)PHP8.0引入JIT编译器,提升性能。4)云原生应用通过Docker和Kubernetes部署,提高灵活性和可扩展性。

PHP与其他语言:比较PHP与其他语言:比较Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP与Python:核心功能PHP与Python:核心功能Apr 13, 2025 am 12:16 AM

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

PHP:网络开发的关键语言PHP:网络开发的关键语言Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP:许多网站的基础PHP:许多网站的基础Apr 13, 2025 am 12:07 AM

PHP成为许多网站首选技术栈的原因包括其易用性、强大社区支持和广泛应用。1)易于学习和使用,适合初学者。2)拥有庞大的开发者社区,资源丰富。3)广泛应用于WordPress、Drupal等平台。4)与Web服务器紧密集成,简化开发部署。

超越炒作:评估当今PHP的角色超越炒作:评估当今PHP的角色Apr 12, 2025 am 12:17 AM

PHP在现代编程中仍然是一个强大且广泛使用的工具,尤其在web开发领域。1)PHP易用且与数据库集成无缝,是许多开发者的首选。2)它支持动态内容生成和面向对象编程,适合快速创建和维护网站。3)PHP的性能可以通过缓存和优化数据库查询来提升,其广泛的社区和丰富生态系统使其在当今技术栈中仍具重要地位。

PHP中的弱参考是什么?什么时候有用?PHP中的弱参考是什么?什么时候有用?Apr 12, 2025 am 12:13 AM

在PHP中,弱引用是通过WeakReference类实现的,不会阻止垃圾回收器回收对象。弱引用适用于缓存系统和事件监听器等场景,需注意其不能保证对象存活,且垃圾回收可能延迟。

解释PHP中的__ Invoke Magic方法。解释PHP中的__ Invoke Magic方法。Apr 12, 2025 am 12:07 AM

\_\_invoke方法允许对象像函数一样被调用。1.定义\_\_invoke方法使对象可被调用。2.使用$obj(...)语法时,PHP会执行\_\_invoke方法。3.适用于日志记录和计算器等场景,提高代码灵活性和可读性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器