我有一个名为“offers”的表,其中有一列名为 start_date
,类型为 dateTime
。
我想将此列拆分为两个单独的列:
start_date
类型date
start_time
类型time
为此,我有以下代码:
<?php
use App\Offer;
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class FixOffersTable extends Migration
{
public function up()
{
Schema::table('offers', function(Blueprint $table)
{
$table->renameColumn('start_date', 'start_date_time');
$table->renameColumn('end_date', 'end_date_time');
});
Schema::table('offers', function (Blueprint $table)
{
$table->date('start_date')->after('start_date_time')->nullable();
$table->time('start_time')->after('start_date')->nullable();
foreach (Offer::all() as $offer) {
/* Cannot use model mutator, as model class can change over time, and may no longer have certain columns
in the $casts attribute. Therefore using the raw string fetched from the MySQL database. */
$startDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $offer->getOriginal('start_date_time'));
$offer->start_date = Carbon::createFromDate($startDateTime->year, $startDateTime->month, $startDateTime->day);
$offer->start_time = Carbon::createFromTime($startDateTime->hour, $startDateTime->minute, $startDateTime->second);
$offer->save();
}
});
}
}
但是上面给出了以下错误:
[Doctrine\DBAL\Schema\SchemaException]
There is no column with name 'start_date' on table 'offers'.
然而,注释掉“for 循环”意味着这个错误不再存在,这意味着问题就在那里。
也欢迎更好的方法!
最佳答案
回答了我自己的问题。我收到此错误的原因有两个。
原因 1,我要求一个列在另一个列之后,但它还不存在。
原因 2,我正在使用尚未创建的列创建报价。
应该这样做:
<?php
use App\Offer;
use App\Schedule;
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class FixOffersTable extends Migration
{
public function up()
{
DB::beginTransaction();
Schema::table('offers', function(Blueprint $table)
{
$table->renameColumn('start_date', 'start_date_time');
$table->renameColumn('end_date', 'end_date_time');
});
Schema::table('offers', function (Blueprint $table)
{
$table->time('start_time')->after('start_date_time')->nullable();
$table->date('start_date')->after('start_date_time')->nullable();
});
foreach (Offer::all() as $offer) {
/* Cannot use model mutator, as model class can change over time, and may no longer have certain columns
in the $casts attribute. Therefore using the raw string fetched from the MySQL database. */
$startDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $offer->getOriginal('start_date_time'));
$offer->start_date = Carbon::createFromDate($startDateTime->year, $startDateTime->month, $startDateTime->day);
$offer->start_time = Carbon::createFromTime($startDateTime->hour, $startDateTime->minute, $startDateTime->second);
$offer->save();
}
DB::commit();
}
}
关于php - 在 Laravel 5 中将 `dateTime` 列拆分为单独的 `date` 和 `time` 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41934852/