I have a table called 'offers' with a column called start_date
of type dateTime
.
I want to split this column into two separate columns called:
start_date
of typedate
start_time
of typetime
To do this I have the following code:
<?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()
{
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();
}
});
}
}
However the above gives the following error:
[Doctrine\DBAL\Schema\SchemaException]
There is no column with name 'start_date' on table 'offers'.
Please help. Better methods is also welcome!
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire