I have a strange problem and an hour of googling and searching through stackoverflow didn't get me any closer to a solution. What happens is that when I trye to seed a table (let's call it my_table
for security purposes) the seeder seems to try to populate columns that I never asked to be seeded.
So, first I run php artisan migrate
to create my table using the following migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateMyTableTable extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('my_table', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user');
$table->tinyInteger('from_default')->nullable(false)->default(7);
$table->tinyInteger('to_default')->nullable(false)->default(20);
$table->timestamps();
$table->unique('user_id');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('my_table', function (Blueprint $table) {
$table->dropUnique(['user_id']);
$table->dropForeign(['user_id']);
});
}
}
This works well, and when I do DESCRIBE my_table
I get the following:
Field Type Null Key Default Extra
-------------------------------------------------------------------------------
id int(10) unsigned NO PRI auto_increment
user_id int(10) unsigned NO UNI
from_default tinyint(4) NO 7
to_default tinyint(4) NO 20
created_at timestamp YES
updated_at timestamp YES
So you can see that the table is created with the exact fields that I want in my migration file. So, now I want to seed this table using the following seed:
<?php
use App\DomainLogic\Models\MyTable;
use App\DomainLogic\Models\User;
use Faker\Factory as FakerFactory;
use Illuminate\Database\Seeder;
class MyTableTableSeeder extends Seeder
{
/**
* @var array list of MyTable Users
*/
private $myTableUsers = [];
/**
* Run the database seeds.
*/
public function run()
{
$this->createMyTableUsers();
$myTableUsers = $this->getMyTableUsers();
foreach ($myTableUsers as $myTableUser) {
factory(MyTable::class)->create([
'user_id' => $myTableUser->getKey(),
'from_default' => 7,
'to_default' => 20,
]);
}
}
private function getMyTableUsers(): array
{
return $this->myTableUsers;
}
private function createMyTableUsers()
{
$faker = FakerFactory::create();
// My table
$this->myTableUsers[] = factory(User::class)->create([
'id' => 2,
'first_name' => 'Kalle',
'last_name' => 'Andersson',
'email' => 'kalle.andersson@email.com',
'password' => bcrypt('password', ['rounds' => 4]),
'mobile_number' => $faker->e164PhoneNumber,
]);
$this->myTableUsers[] = factory(User::class)->create([
'id' => 3,
'first_name' => 'Johan',
'last_name' => 'Petterson',
'email' => 'johan.petterson@email.com',
'password' => bcrypt('password', ['rounds' => 4]),
'mobile_number' => $faker->e164PhoneNumber,
]);
$this->myTableUsers[] = factory(User::class)->create([
'id' => 4,
'first_name' => 'Krister',
'last_name' => 'Johansson',
'email' => 'krister.johansson@email.com',
'password' => bcrypt('password', ['rounds' => 4]),
'mobile_number' => $faker->e164PhoneNumber,
]);
$this->myTableUsers[] = factory(User::class)->create([
'id' => 5,
'first_name' => 'Daniel',
'last_name' => 'Eriksson',
'email' => 'daniel.eriksson@email.com',
'password' => bcrypt('password', ['rounds' => 4]),
'mobile_number' => $faker->e164PhoneNumber,
]);
}
}
When running php artisan db:seed
I get this error:
In Connection.php line 664:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'starts_day_default' in 'field list' (SQL: insert into `my_table` (`user_id`, `starts_day_default`, `ends_day_default`, `from_default`, `to_default`) values (2, 07, 20, 7, 20))
In PDOConnection.php line 82:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'starts_day_default' in 'field list'
In PDOConnection.php line 80:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'starts_day_default' in 'field list'
So the strange thing is that as far as I see, I never try to populate a column called starts_day_default
or ends_day_default
. Because those columns don't exist and should not exist. The actual thing is that the columns were renamed starts_day_default -> from_default
and ends _day_default -> to_default
. The users are created correctly, I can see them in the users table, so that is not the problem. Here is also my model for MyTable:
<?php
namespace App\DomainLogic\Models;
use DateTimeImmutable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class MyTable extends Model
{
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'my_table';
/**
* Creates personal trainer, if personal trainer with id exists.
*
* @param int $myTableId
*
* @return null|self
*/
public static function createFromId(int $myTableId): ?self
{
$myTable = self::select('my_table.*')
->join('user', 'user.id', '=', 'my_table.user_id')
->where('my_table.id', '=', $myTableId)
->whereNull('user.anonymized_at')
->get()
->first();
return $myTable;
}
/**
* Create personal trainer, if user_id exists.
*
* @param int $userId
*
* @return null|MyTable
*/
public static function createFromUserId(int $userId): ?self
{
return self::where('user_id', $userId)->get()->first();
}
/**
* Gets all personal trainers.
*
* @param bool $active
*
* @return Collection
*/
public static function getMyTables(bool $active = null): Collection
{
$query = self::select('my_table.*')
->join('user', 'user.id', '=', 'my_table.user_id')
->whereNull('user.anonymized_at');
if (isset($active)) {
$query->where('user.active', '=', $active);
}
$myTables = $query->get();
return $myTables;
}
/**
* Gets user.
*/
public function getUser(): User
{
$user = $this->belongsTo(User::class, 'user_id', 'id')->getResults();
return $user;
}
/**
* Check if personal trainers ids are valid.
*
* @param array $myTableIds
*
* @return bool
*/
public static function areMyTableIdsValid(array $myTableIds): bool
{
$dbMyTableIds = self::select('my_table.id')
->join('user', 'user.id', '=', 'my_table.user_id')
->whereIn('my_table.id', $myTableIds)
->whereNull('user.anonymized_at')
->get()
->pluck('id')
->toArray();
$dbMyTableIds = array_map('intval', $dbMyTableIds);
sort($myTableIds);
sort($dbMyTableIds);
$result = false;
if ($myTableIds === $dbMyTableIds) {
$result = true;
}
return $result;
}
}
I have tried
php artisan view:clear
php artisan cache:clear
php artisan debugbar:clear
composer dump-autoload
suggested in Unknown column 'username' in Laravel but that did not help. I have dropped all tables and rerun php artisan migrate
but that did not help either.
I have never seen this before, so my question is, can anyone see what my problem is?
Finally solved it, I missed that there was a factory file MyTableFactory
that still contained the faulty columns. The file was very hidden.