`

laravel5.2 修改已有的表(之后在文档中发现另一个方法)

 
阅读更多

比如我有一个imgs表,现在在这个表中添加一个votes字段

 

php artisan make:migration add_votes_to_imgs_table --table=imgs

 

然后修改生成的migration文件

    public function up()

    {

        Schema::table('imgs', function (Blueprint $table) {

            $table->integer('votes');

        });

    }

 

最后php artisan migrate

 

如果直接改table的话,就不用以上几步了,然后可以直接修改对应的model

 

 

 

laravel文档中还有一种不修改表的方法

Attribute Casting

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast, while the value is the type you wish to cast the column to. The supported cast types are: integerrealfloatdoublestringbooleanobjectarraycollectiondatedatetime, and timestamp.

For example, let's cast the is_admin attribute, which is stored in our database as an integer (0 or1) to a boolean value:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'is_admin' => 'boolean',
    ];
}

Now the is_admin attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:

$user = App\User::find(1);

if ($user->is_admin) {
    //
}
分享到:
评论

相关推荐

    Laravel 5.2 文档 数据库 —— 起步介绍

    而`update`方法则用于更新数据库中的已有记录,它返回受影响的行数。与`update`类似,`delete`方法用于删除记录,并返回被删除的行数。对于那些不返回值的数据库操作,Laravel的`statement`方法可以用来执行这些操作...

    api-guard:使用Laravel使用API​​密钥对RESTful API进行身份验证的简单方法

    此外,从Laravel 7.x开始,有一个名为的新Laravel软件包,可以更好地满足API身份验证的目的。 使用Laravel使用API​​密钥对API进行身份验证的简单方法。 该软件包使用以下库: philsturgeon的 maximebeaudoin的 ...

    DebugBar插件

    例如,如果你正在使用Laravel 5.2,那么DebugBar v5.2.2应该是一个合适的版本。 2. **安装与配置**:按照官方文档或相关教程进行安装,通常通过Composer(PHP依赖管理工具)来添加DebugBar到项目中,并在配置文件中...

    社团管理系统报告.docx

    在社团管理系统中,数据流可能包括社团申请、成员报名、活动发布、财务管理等多个流程。 2.3 数据字典 数据字典是对系统中所有数据元素的详细描述,包括数据项的名称、含义、来源、格式和使用情况。 3. 概念结构...

    php 入门手册 .

    良好的错误处理机制有助于调试和提升程序稳定性。 9. **面向对象编程** 自PHP 5起,支持面向对象编程,包括类、对象、继承、封装和多态。`class`关键字定义类,`new`关键字实例化对象。 10. **PHP与Web框架** ...

Global site tag (gtag.js) - Google Analytics