我有一个名为'offers'的表,其中有一个名为start_date
的列,类型为dateTime
。
我要将此列拆分为两个单独的列,称为:start_date
类型date
类型
为此,我有以下代码:
<?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,我正在使用尚未创建的列创建offers。
应该这样做:
<?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/