【问题标题】:Laravel update database table designLaravel 更新数据库表设计
【发布时间】:2016-11-26 08:42:27
【问题描述】:

我有一个 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?

我期待听到我能做些什么:)

【问题讨论】:

标签: php mysql laravel migration


【解决方案1】:

你需要添加迁移:

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

更多信息和可用的列类型here

【讨论】:

  • 你知道这在 one.com 服务器上是否可行吗?
  • one.com 提供 ssh 访问,因此您可以在服务器上运行命令
  • 好的,谢谢,有机会我会试试的。运行最后一个命令后,我的 Players 表 + 模型会自动更新吗?
  • 表格将更新,新字段将可访问
  • 所以在我运行命令后,我需要在“可填充”数组中添加新字段,然后我可以在我的控制器中访问它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 2021-04-27
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
相关资源
最近更新 更多