Laravel 迁移 - 创建一个从现有列填充的新列
Laravel Migration - Create a new column filled from existing column
我正在尝试创建一个创建新列并用现有列中的数据填充它的迁移。
我想将名称列变成一个 slug(使用辅助函数)并将其保存在一个 slug 列中。
我已经试过了,但没有成功:
public function up()
{
Schema::table('teams', function(Blueprint $table)
{
//
$table->string('slug', 100);
});
$teams = DB::table('teams')->get();
foreach ($teams as $team)
{
$team->slug = str_slug($team->name, "-");
$team->save();
}
}
我是白痴吗?我可以做这个吗?
谢谢
您没有使用 name
列,而是(空的)slug
。试试这个:
$team->slug = str_slug($team->name, "-");
假设您有一个 Team
模型:
$teams = App\Team::all();
foreach($teams as $team) {
$team->slug = str_slug($team->name, "-");
$team->save();
}
您正试图在实际使用查询生成器的代码中使用 Eloquent ORM 语法 ($team->save
)。您最好选择其中之一(ORM 或查询构建)。我的版本使用 Eloquent ORM。当然,您可以一直使用 Query Builder 语法,如下所示:
$teams = DB::table('teams');
foreach($teams as $team) {
DB::table('teams')
->where('id', $team->id)
->update(['slug' => str_slug($team->name)]);
}
基本上,查询生成器 select 命令(如 $teams = DB::table('teams');
)将 return stdClass 对象数组(没有 "save" 方法),而 Eloquent ORM select 将 return 指定模型的对象集合,这些对象确实具有 "save" 方法。
我正在尝试创建一个创建新列并用现有列中的数据填充它的迁移。
我想将名称列变成一个 slug(使用辅助函数)并将其保存在一个 slug 列中。
我已经试过了,但没有成功:
public function up()
{
Schema::table('teams', function(Blueprint $table)
{
//
$table->string('slug', 100);
});
$teams = DB::table('teams')->get();
foreach ($teams as $team)
{
$team->slug = str_slug($team->name, "-");
$team->save();
}
}
我是白痴吗?我可以做这个吗?
谢谢
您没有使用 name
列,而是(空的)slug
。试试这个:
$team->slug = str_slug($team->name, "-");
假设您有一个 Team
模型:
$teams = App\Team::all();
foreach($teams as $team) {
$team->slug = str_slug($team->name, "-");
$team->save();
}
您正试图在实际使用查询生成器的代码中使用 Eloquent ORM 语法 ($team->save
)。您最好选择其中之一(ORM 或查询构建)。我的版本使用 Eloquent ORM。当然,您可以一直使用 Query Builder 语法,如下所示:
$teams = DB::table('teams');
foreach($teams as $team) {
DB::table('teams')
->where('id', $team->id)
->update(['slug' => str_slug($team->name)]);
}
基本上,查询生成器 select 命令(如 $teams = DB::table('teams');
)将 return stdClass 对象数组(没有 "save" 方法),而 Eloquent ORM select 将 return 指定模型的对象集合,这些对象确实具有 "save" 方法。