I set user table as below
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email')->unique();
$table->string('password')->nullable();
$table->tinyInteger('status')->unsigned()-> nullable(false) -> change()->default(1);
$table->string('confirmation_code')->nullable();
$table->tinyInteger('confirmed')->unsigned()->nullable(false) -> change()->default(1);
$table->rememberToken();
$table->unsignedInteger('deleted_at');
$table->timestamps();
});
}
but show error as below
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name '' (SQL: alter table `` add `status` tinyint unsigned not null default '1' after `password`, add `confirmation_code` varchar(255) null after `status`, add `confirmed` tinyint(1) not null default '1' after `confirmation_code`, add `deleted_at` timestamp null)
at C:\xampp\htdocs\cron\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name ''")
C:\xampp\htdocs\cron\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452
2 PDO::prepare("alter table `` add `status` tinyint unsigned not null default '1' after `password`, add `confirmation_code` varchar(255) null after `status`, add `confirmed` tinyint(1) not null default '1' after `confirmation_code`, add `deleted_at` timestamp null")
C:\xampp\htdocs\cron\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452
Please use the argument -v to see more details.
please help me to correct this migration.
I think I wrong in not null
You shouldn't be using the ->change() method in Schema::create(), as it will try to change a column that hasn't been created yet. To create a column that allows null values, simply do:
Schema::create("table", function (Blueprint $table) {
$table->string("column"); // Omit ->nullable() to force `NOT NULL`
$table->string("nullable_column")->nullable();
});
When this migration is run, and the table is created, table.column will be initialized with NOT NULL, and table.nullable_column will be initialized as NULL.
Now, if you need to change these in a later migration, that is when you use ->nullable(false)->change();, like so:
Schema::table("table", function (Blueprint $table) {
$table->string("column")->nullable()->change();
$table->string("nullable_column")->nullable(false)->change();
});
Following this migration, table.column will allow NULL, while table.nullable_column will not.
Related
I have the following migration (for a pivot table):
Schema::create('category_news', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('category_id');
$table->unsignedBigInteger('news_id');
$table->unique(['category_id', 'news_id']);
$table->foreign('news_id')->references('id')->on('news')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
I want to seed that table with some dummy data -- to do so, I have created the following factory:
$factory->define(CategoryNews::class, function (Faker $faker) {
return [
'category_id' => $faker->numberBetween($min = 1, $max = 35),
'news_id' => $faker->numberBetween($min = 1, $max = 150)
];
});
However, when I run the following command: php artisan migrate:fresh --seed, I get the following error:
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE) (SQL: insert into `category_news` (`category_id`, `news_id`, `updated_at`, `created_at`) values (16, 13, 2020-03-31 10:44:04, 2020-03-31 10:44:04))
at C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
1 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOException::("SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`startup-reporter`.`category_news`, CONSTRAINT `category_news_news_id_foreign` FOREIGN KEY (`news_id`) REFERENCES `news` (`id`) ON DELETE CASCADE)")
2 C:\laragon\www\startup-reporter\vendor\laravel\framework\src\Illuminate\Database\Connection.php:463
PDOStatement::execute()
Any idea why and what I need to do to fix it?
Thanks.
I figured it out -- I had to reorder my DatabaseSeeder.php file to call the NewsTableSeeder file before I called the CategoryNewsTableSeeder file.
you are trying to add a new record category_news with category_id=16
while you don't have a category with id =16, so the constraint will throw an error ...
you can't use random int to assign it to your foreign keys references ...
you can simply do something like this:
$factory->define(CategoryNews::class, function (Faker $faker) {
return [
'category_id' => Category::all()->random()->id,
'news_id' => News::all()->random()->id,
];
});
i have found this way here :
https://stackoverflow.com/a/44102531/10573560
I am trying to insert 'employee_id' that belongs to employees table into payrolls table, but i keep getting this error despite having $fillable = ['over_time', 'notified','hours','rate', 'gross', 'employee_id'], is there any other solution to this?
Schema::create('payrolls', function (Blueprint $table) {
$table->bigIncrements('id'); $table->boolean('over_time')->default(0);
$table->boolean('notified')->default(0);
$table->integer('hours')->nullable(0);
$table->integer('rate')->nullable(0);
$table->integer('gross')->nullable(0);
$table->softDeletes(); $table->timestamps();
});
As per your migration you have defined hours columns nullable false that means it cannot be null and also no default value is defined for that column.
Due to some reason your hours is going blank in your request that is why you are getting this error.
$table->integer('hours')->nullable(0);
To resolve this either define default value to your hour column as below or pass a valid value to hours column
$table->integer('hours')->default("00");
I want to create a table with multiple foreign keys. Here is the sql:
CREATE TABLE `customers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`address` varchar(100) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`type_id` tinyint(3) unsigned DEFAULT NULL,
`district_id` tinyint(3) unsigned DEFAULT NULL,
`city_id` tinyint(3) unsigned DEFAULT NULL,
`business_id` tinyint(3) unsigned DEFAULT NULL,
`group_id` tinyint(3) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_customer_1` (`district_id`,`city_id`),
KEY `FK_customer_2` (`business_id`),
KEY `FK_customer_3` (`group_id`),
KEY `FK_customer_4` (`type_id`),
CONSTRAINT `FK_customer_1` FOREIGN KEY (`district_id`, `city_id`)
REFERENCES `cities` (`district_id`, `city_id`) ON DELETE CASCADE,
CONSTRAINT `FK_customer_2` FOREIGN KEY (`business_id`) REFERENCES `businesses` (`business_id`) ON DELETE CASCADE,
CONSTRAINT `FK_customer_3` FOREIGN KEY (`group_id`) REFERENCES `groups` (`group_id`) ON DELETE CASCADE,
CONSTRAINT `FK_customer_4` FOREIGN KEY (`type_id`) REFERENCES `types` (`type_id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
I wrote a migration file with the following:
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('name',50);
$table->string('address',100)->nullable();
$table->string('email',50)->nullable();
$table->integer('type_id')->unsigned()->index();
$table->integer('district_id')->unsigned()->index();
$table->integer('city_id')->unsigned()->index();
$table->integer('business_id')->unsigned()->index();
$table->integer('group_id')->unsigned()->index();
$table->timestamps();
$table->foreign(['district_id','city_id'])->references(['district_id','city_id'])->on('cities')->onDelete('cascade');
$table->foreign('business_id')->references('business_id')->on('businesses')->onDelete('cascade');
$table->foreign('type_id')->references('type_id')->on('types')->onDelete('cascade');
$table->foreign('group_id')->references('group_id')->on('groups')->onDelete('cascade');
});
But when I run the migration it gives me the following error.
SQLSTATE[HY000]: General error: 1005 Can't create table `wastewater`.`#sql-5a8_18a` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `customers` add constraint `customers_district_id_city_id_foreign` foreign key (`district_id`, `city_id`) references `cities` (`district_id`, `city_id`) on delete cascade)`
How can I this?
Can you please Try this way, Just removed array and define with comma-separated only.
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->string('name',50);
$table->string('address',100)->nullable();
$table->string('email',50)->nullable();
$table->integer('type_id')->unsigned()->index();
$table->integer('district_id')->unsigned()->index();
$table->integer('city_id')->unsigned()->index();
$table->integer('business_id')->unsigned()->index();
$table->integer('group_id')->unsigned()->index();
$table->timestamps();
$table->foreign('district_id','city_id')->references('district_id','city_id')->on('cities','cities')->onDelete('cascade','cascade');
$table->foreign('business_id')->references('business_id')->on('businesses')->onDelete('cascade');
$table->foreign('type_id')->references('type_id')->on('types')->onDelete('cascade');
$table->foreign('group_id')->references('group_id')->on('groups')->onDelete('cascade');
});
Try the following way, it will work.
Schema::create('customers', function (Blueprint $table) {
$table->increments('id');
$table->integer('type_id', false, true);
$table->foreign('type_id')->references('type_id')->on('types')
->onDelete('cascade');
$table->integer('district_id', false, true);
$table->foreign('district_id')
->references('district_id')->on('cities')
->onDelete('cascade');
$table->integer('city_id', false, true);
$table->foreign('city_id')
->references('city_id')->on('cities')
->onDelete('cascade');
$table->integer('business_id', false, true);
$table->foreign('business_id')->references('business_id')
->on('businesses')->onDelete('cascade');
$table->integer('group_id', false, true);
$table->foreign('group_id')->references('group_id')->on('groups')
->onDelete('cascade');
$table->string('name',50);
$table->string('address',100)->nullable();
$table->string('email',50)->nullable();
$table->timestamps();
});
Using Laravel 5.3 how can I implement partition. Following is the mysql table structure I'm trying to add in migration.
CREATE TABLE `settings` (
`id` INT(10) unsigned NOT NULL AUTO_INCREMENT,
`client_id` INT(11) NOT NULL,
`key` VARCHAR(255) COLLATE utf8_unicode_ci NOT NULL,
`value` TEXT COLLATE utf8_unicode_ci NOT NULL,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY `settings_id_primary` (`client_id`, `id`),
UNIQUE KEY `settings_key_unique` (`client_id`, `key`),
KEY `settings_id_key` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci PARTITION BY KEY (`client_id`) PARTITIONS 50;
Below is what I tried so far, but this is only adding columns & keys.
Schema::create('settings', function(Blueprint $table) {
$table->integer('id'); // I can't use increments, because throwing an error when I try to add primary key below
$table->integer('client_id');
$table->string('key');
$table->text('value');
$table->timestamps();
$table->primary(['client_id', 'id']);
$table->unique(['client_id', 'key']);
});
How can I do the partition? If there migration doesn't support partition. Is there way I can dump the whole SQL query in the migration and run.
I think it is help to you,
Schema::create('settings', function(Blueprint $table) {
$table-> increments('id');
$table->integer('client_id')->primary();
$table->string('key');
$table->text('value');
$table->timestamps();
$table->unique(['client_id', 'key']);
});
or
Schema::create('settings', function(Blueprint $table) {
$table-> increments('id');
$table->integer('client_id');
$table->string('key');
$table->text('value');
$table->timestamps();
$table->primary('client_id');
$table->unique(['client_id', 'key']);
});
I searched everywhere, i can't solution find for partition.
But,
My suggestion use, below unprepared into the migration file functions of up and down function
DB::unprepared()
in migration to run your SQL query with partition.
like,
DB::unprepared('create table....')
There's now a Composer package for this called brokenice/laravel-mysql-partition:
https://packagist.org/packages/brokenice
Here's a sample right from the docs:
// You use their extended Schema class:
use Brokenice\LaravelMysqlPartition\Schema\Schema;
// You might also need this (I didn't need it for partitioning by hash):
use Brokenice\LaravelMysqlPartition\Models\Partition;
// I omitted class and method definition boilerplate...
// Create a table as you would normally:
Schema::create('partitioned', static function (Blueprint $table) {
// ...
});
// Now partition it (it will run an ALTER TABLE query):
Schema::partitionByList(
'partitioned',
'id',
[
new Partition('server_east', Partition::LIST_TYPE, [1,43,65,12,56,73]),
new Partition('server_west', Partition::LIST_TYPE, [534,6422,196,956,22])
]
);
I am trying to add a new "dateTime" field to my posts table :
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->dateTime('published_at');
});
}
but when I execute php artisan migrate I get the error :
[Illuminate\Database\QueryException]
SQLSTATE[23502]: Not null violation: 7 ERROR: column "published_at" contains null values (SQL: alter table "posts" add column "publish
ed_at" timestamp(0) without time zone not null)
[PDOException]
SQLSTATE[23502]: Not null violation: 7 ERROR: column "published_at" contains null values
What's wrong here ?
$table->dateTime('published_at')->nullable();
Why not use $table->timestamps(); it makes a created_at column just as the dateTime() type does and also makes an updated_at column which is ideal for posts that may be edited.