Laravel更新数据库表设计

6 浏览
0 Comments

Laravel更新数据库表设计

我有一个php laravel项目,需要在一个或多个模型(Eloquent)中添加一个字段。我在php方面没有太多经验,以前也没有尝试过laravel。

现在这个类看起来像这样

class Player extends Eloquent
{
use GenderTrait;
use VisibilityTrait;
use PlayerPhotoTrait;
use PlayerActionTrait;
const GENDER_MALE = 2;
const GENDER_FEMALE = 1;
/**
 * The database table used by model.
 *
 * @var string
 */
protected $table = 'players';
/**
 * Parameters for `actions` relation.
 *
 * @see PlayerActionTrait::actions()
 * @var array
 */
protected $actionModel = [
    'name' => 'PlayerAction',
    'foreignKey' => 'player_id',
];
/**
 * The list of mass-assignable attributes.
 *
 * @var array
 */
protected $fillable = [
    'name',
    'start_value',
    'gender',
    'is_visible',
    'nation',
];
/**
 * The list of validation rules.
 *
 * @var array
 */
public static $rules = [
    'name' => 'required',
    'nation' => 'required|numeric',
    'start_value' => 'required|numeric',
];
/**
 * @inheritdoc
 */
protected static function boot()
{
    parent::boot();
}
/**
 * Players country.
 *
 * @return Country
 */
public function country()
{
    return $this->belongsTo('Country', 'nation');
}
/**
 * Player videos.
 *
 * @return mixed
 */
public function videos()
{
    return $this->morphMany('YoutubeLink', 'owner');
}
}

我想添加一个名为“level”的字符串字段,但我不知道该如何做。如果我先在MySQL中创建字段,然后更新模型,laravel会为我更新MySQL吗?

我期待着听到我可以做什么:)

admin 更改状态以发布 2023年5月23日
0
0 Comments

你需要添加一个迁移:

php artisan make:migration add_fields_to_players_table --table=players

/database/migrations路径下新建一个迁移,并填写代码:

Schema::table('players', function ($table) {
    $table->string('new_string_field');
});

现在需要运行迁移:

php artisan migrate

更多信息和可用列类型,请参阅此处

0