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) {
    //
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值