I am using two pivot tables to store two different relations of a table. One relation works fine on insert. but the next one throws the following error. I don't know what's causing this.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (sdesk.approvers, CONSTRAINT approvers_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into approvers (user_id, request_id, updated_at, created_at) values (2, 6, 2014-04-29 10:54:37, 2014-04-29 10:54:37))
Here's my code:
UrequestsController.php
public function postCreate() {
$request = new Urequest;
$request->vms = Input::get('vms');
$request->location = Input::get('location');
$request->descr = Input::get('descr');
$request->status = Input::get('status');
//$request->role_group = Input::get('team');
$request->save();
$ruser = new Ruser;
$ruser->user_id = Input::get('userid');
$ruser->urequest()->associate($request);
$ruser->save();
$approver = new Approver;
$approver->user_id = Input::get('aid');
$approver->urequest()->associate($request);
$approver->save();
return Redirect::to('users/dashboard')->with('message', 'Saved!');
}
Approver.php
class Approver extends Eloquent {
protected $fillable = array('request_id', 'user_id');
public function urequest() {
return $this->belongsTo('Urequest','request_id');
}
}
Ruser.php
class Ruser extends Eloquent {
protected $fillable = array('request_id', 'user_id');
public function urequest() {
return $this->belongsTo('Urequest','request_id');
}
}
urequest.php
class Urequest extends Eloquent {
protected $table = 'requests';
protected $fillable = array('vms', 'location', 'descr', 'status');
public function ruser() {
return $this->hasOne('Ruser');
}
public function approver() {
return $this->hasOne('Approver');
}
}
Schema
Schema::create('requests', function($table)
{
$table->increments('id');
$table->string('vms', 20);
$table->string('location', 20);
$table->string('descr', 255);
$table->string('status', 20);
$table->timestamps();
});
Schema::create('rusers', function($table)
{
$table->increments('id');
$table->integer('request_id')->unsigned();
$table->foreign('request_id')->references('id')->on('requests');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
Schema::create('approvers', function($table)
{
$table->increments('id');
$table->integer('request_id')->unsigned();
$table->foreign('request_id')->references('id')->on('requests');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
"A foreign key constraint" usually fails when you don't have a row for the value(s) you are inserting/updating in the foreign table.
In this case you probably doesn't have a user_id of 2 in the users table or a request_id of 6 in the requests table.
EDIT just saw morawcik answered it in comments.
Related
I am currently learning Laravel through a personal project.
Context
In a blog like application, I need to link an article to its author. When I save the article, I get the error below.
Error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (parabolica-dev.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into articles (title, content, excerpt, updated_at, created_at) values (rgergregerg, regergergregerg, regregregregreg, 2020-04-29 09:55:12, 2020-04-29 09:55:12))
Models
Article
class Article extends Model
{
protected $fillable = ['title', 'content', 'excerpt', 'user_id'];
public function user() {
return $this->belongsTo('App\User');
}
}
User
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
public function article()
{
return $this->hasMany('App\Article');
}
}
Migrations
Users
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
Articles
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title');
$table->text('excerpt');
$table->text('content');
$table->string('type');
$table->string('status');
// Relationship between article and user
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
Controller
ArticleController
class ArticleController extends Controller
{
public function store(StoreArticle $request)
{
$validatedData = $request->validated();
$user = Auth::user()->id;
$article = Article::create($validatedData);
$article->user_id = $user;
$request->session()->flash('status', 'Article was created!');
return redirect()->route('articles.show', ['article' => $article->id]);
}
}
Solutions tried
Adding user_id to the $fillable array in my Article model, I still get the error.
Adding the nullable() method to user_id in my migration. Saving the article goes through without the error message but the user_id is recorded as null in my table afterwards.
Those are the 2 most proposed solutions across SO / LaravelCasts from what I found. Any suggestions on what I did wrong ?
Thanks for helping me !
The create method creates and saves a new instance of your model. Since the model does not include the users id at that point, it fails.
You could fix that by adding user_id to the fillables array of your model and also add the user id to the $validatedData array before creating the model.
Alternatively, you can also create a new instance of your model with the new keyword, set all data and explicitely save it once you're done:
$article = new Article($validatedData);
$article->user()->associate( Auth::user() );
$article->save();
You have to change this three lines. You insert a row but at the time user_id is null. That's why it shows the error because you assigned the user_id field not nullable.
$article = new Article;
$article->fill($validatedData);
$article->user_id = Auth::user()->id;
$article->save();
I am currently learning Laravel through a personal project.
Context
In a blog like application, I need to link an article to its author. When I save the article, I get the error below.
Error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (parabolica-dev.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id)) (SQL: insert into articles (title, content, excerpt, updated_at, created_at) values (rgergregerg, regergergregerg, regregregregreg, 2020-04-29 09:55:12, 2020-04-29 09:55:12))
Models
Article
class Article extends Model
{
protected $fillable = ['title', 'content', 'excerpt', 'user_id'];
public function user() {
return $this->belongsTo('App\User');
}
}
User
class User extends Authenticatable
{
protected $fillable = [
'name', 'email', 'password',
];
public function article()
{
return $this->hasMany('App\Article');
}
}
Migrations
Users
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
Articles
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('title');
$table->text('excerpt');
$table->text('content');
$table->string('type');
$table->string('status');
// Relationship between article and user
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::dropIfExists('articles');
}
}
Controller
ArticleController
class ArticleController extends Controller
{
public function store(StoreArticle $request)
{
$validatedData = $request->validated();
$user = Auth::user()->id;
$article = Article::create($validatedData);
$article->user_id = $user;
$request->session()->flash('status', 'Article was created!');
return redirect()->route('articles.show', ['article' => $article->id]);
}
}
Solutions tried
Adding user_id to the $fillable array in my Article model, I still get the error.
Adding the nullable() method to user_id in my migration. Saving the article goes through without the error message but the user_id is recorded as null in my table afterwards.
Those are the 2 most proposed solutions across SO / LaravelCasts from what I found. Any suggestions on what I did wrong ?
Thanks for helping me !
The create method creates and saves a new instance of your model. Since the model does not include the users id at that point, it fails.
You could fix that by adding user_id to the fillables array of your model and also add the user id to the $validatedData array before creating the model.
Alternatively, you can also create a new instance of your model with the new keyword, set all data and explicitely save it once you're done:
$article = new Article($validatedData);
$article->user()->associate( Auth::user() );
$article->save();
You have to change this three lines. You insert a row but at the time user_id is null. That's why it shows the error because you assigned the user_id field not nullable.
$article = new Article;
$article->fill($validatedData);
$article->user_id = Auth::user()->id;
$article->save();
This question has already been asked many times, I went through all the answers, but none solves the error I'm getting.
I'm using Laravel 5.2
I have 2 tables - Classifieds and Categories. When I want to create a classified, I get the error message:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (myclassified.classifieds, CONSTRAINT classifieds_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id))
Migration files defined like this:
for classifieds table:
public function up()
{
Schema::create('classifieds', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('description');
$table->string('price');
$table->timestamps();
});
}
public function down()
{
Schema::drop('classifieds');
}
for categories table:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('categories');
}
and to add the foreign key,
public function up()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
});
}
public function down()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->dropForeign('classifieds_category_id_foreign');
});
}
The Models are:
Classified model:
class Classified extends Model
{
protected $table = 'classifieds';
protected $fillable = ['title', 'category_id', 'description', 'price'];
protected $hidden = [];
public function category(){
return $this->belongsTo('App\Category');
}
}
and the Category model:
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name'];
protected $hidden = [];
public function classifieds(){
return $this->hasMany('App\Classified');
}
}
and the store method in controller is defined like this:
public function store(Request $request)
{
$title = $request->input('title');
$category_id = $request->input('category_id');
$description = $request->input('description');
$price = $request->input('price');
Classified::create([
'title' => $this->title,
'category_id' => $this->category_id,
'description' => $this->description,
'price' => $this->price
]);
return \Redirect::route('classifieds.index')
->with('message', 'Ad created');
}
What is my mistake in database set up?
This happens, when you are trying to save Classified and assign the foreign key with an id of category that does not exist yet in Category table.
If you don't have the foreign ID yet, just leave it to be null and make sure you do this on migration to allow null values;
public function up()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('set null');
});
}
public function down()
{
Schema::table('classifieds', function(Blueprint $table) {
$table->dropForeign('classifieds_category_id_foreign');
});
}
I have one foreign key in my database named images.
This is its Migration:
class CreateImagesTable extends Migration
{
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->integer('product_r_id')->unsigned();
$table->string('name', 50);
$table->text('images', 50);
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
Schema::table('images', function (Blueprint $table) {
$table->foreign('product_r_id')->references('id')->on('products_r')->onDelete('cascade')->onUpdate('cascade');
});
}
public function down()
{
Schema::drop('images');
}
}
Its Model looks like this:
class Images extends Model
{
protected $table = 'images';
protected $fillable = ['product_id', 'product_r_id', 'name', 'images'];
public function product()
{
return $this->belongsTo('App\Product', 'product_id');
}
public function productR()
{
return $this->belongsTo('App\ProductR', 'product_r_id');
}
}
ProductR Model looks like this:
class ProductR extends Model
{
protected $table = 'products_r';
protected $fillable = ['email', 'title', 'filename', 'inputMpg', 'number_of_chapters'];
public function images()
{
return $this->hasMany('App\Images');
}
}
And Product Model like this:
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['email', 'title', 'filename', 'inputMpg', 'number_of_chapters'];
public function scenesImages()
{
return $this->hasMany('App\Images');
}
}
So I basicaly try to save in two different forms different products with their image into the same table in my database (images).
Running my Program returns me this error:
QueryException in Connection.php line 655: SQLSTATE[23000]: Integrity
constraint violation: 1452 Cannot add or update a child row: a foreign
key constraint fails (mydb.images, CONSTRAINT
images_product_id_foreign FOREIGN KEY (product_id) REFERENCES
products (id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert
into images (name, images, product_r_id, updated_at,
created_at) values (ki, 0Chrysanthemum.jpg, 10, 2016-05-20 10:50:51,
2016-05-20 10:50:51))
I think the issue arises because of these lines:
$table->integer('product_id')->unsigned();
[...]
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade')->onUpdate('cascade');
You cannot just create an image without filling out product_id which seems to be the case because the error
insert into images (name, images, product_r_id, updated_at, created_at) ...
shows that you're inserting into images without product_id which cannot be null and has a foreign key constraint.
I suppose you can do a
$table->integer('product_id')->unsigned()->nullable();
so you don't need to assign it when inserting.
I have created the following migration for lang:
class CreateLangTable extends Migration
{
public function up()
{
Schema::create('lang', function (Blueprint $table) {
$table->string('code')->primary();
$table->string('name');
$table->timestamps();
});
}
}
class CreateMachineryCategoriesTranslationTable extends Migration
{
public function up()
{
Schema::create('machinery_categories_translation', function (Blueprint $table) {
$table->increments('id');
$table->string('lang_code')->index();
$table->foreign('lang_code')->references('code')->on('lang')->onDelete('cascade')->onUpdate('cascade');
$table->integer('machinery_categories_id')->unsigned()->index();
$table->foreign('machinery_categories_id')->references('id')->on('machinery_categories')->onDelete('cascade')->onUpdate('cascade');
$table->string('name')->nullable();
$table->timestamps();
});
}
But when I try to seed with:
class MachineryCategoriesTranslationTableSeeder extends Seeder
{
public function run()
{
$el = Lang::find('el');
$en = Lang::find('en');
$loaderCat = new MachineryCategory();
$loaderCat->save();
$loaderCatEl = new MachineryCategoriesTranslation();
$loaderCatEl->machineryCategories()->associate($loaderCat);
$loaderCatEl->lang()->associate($el);
$loaderCatEl->name = 'Φορτωτές';
$loaderCatEl->save();
$loaderCatEn = new MachineryCategoriesTranslation();
$loaderCatEn->machineryCategories()->associate($loaderCat);
$loaderCatEn->lang()->associate($en);
$loaderCatEn->name = 'Loaders';
$loaderCatEn->save();
}
}
I get the error
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`ps4cat`.`machinery_categories_translation`, CONSTRAINT `machinery_categories_translation_lang_code_foreign` FOREIGN KEY (`lang_code`) REFERENCES `lang` (`code`) ON DELETE CASCADE ON UPDATE CA)
(SQL: insert into `machinery_categories_translation` (`machinery_categories_id`, `lang_code`, `name` , `updated_at`, `created_at`) values (1, 0, Φορτωτές, 2016-04-08 16:24:06, 2016-04-08 16:24:06))
Where the 0 in values for lang_code is clearly wrong. What is the issue?