`

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) {
    //
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics