I am trying to insert values into my comments table and I am getting a error. Its saying that I can not add or update child row and I have no idea what that means.
m
Also make sure that the foreign key you add is the same type of the original column, if the column you're reference is not the same type it will fail too.
I hope my decision will help. I had a similar error in Laravel. I added a foreign key to the wrong table.
Wrong code:
Schema::create('comments', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->index()->nullable();
...
$table->foreign('post_id')->references('id')->on('comments')->onDelete('cascade');
});
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
...
});
Please note to the function on('comments') above. Correct code
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
I had this issue when I was accidentally using the WRONG "uuid" in my child record. When that happens the constraint looks from the child to the parent record to ensure that the link is correct. I was generating it manually, when I had already rigged my Model to do it automatically. So my fix was:
$parent = Parent:create($recData); // asssigning autogenerated uuid into $parent
Then when I called my child class to insert children, I passed this var value:
$parent->uuid
Hope that helps.
that means that the value for column project_id
on table comments
you are inserting not only doesn't exist
on table projects BUT also project_id
probably doesn't have default value. E.g. in my case I set it as NULL.
As for Laravel you can consider this expressions as a chunk of code of a migration php file, for example:
class ForeinToPhotosFromUsers extends Migration
{ /** * Run the migrations. * * @return void */
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('photo_id')->nullable();// ! ! ! THIS STRING ! ! !
$table->foreign('photo_id')->references('id')->on('photos');
});
}
}
Obviously you had to create the Model class(in my case it was Photo) next to all these.
Make sure you have project_id
in the fillable
property of your Comment
model.
I had the same issue, And this was the reason.
If you are adding new foreign key to an existing table and the columns are not null and not assigned default value, you will get this error,
Either you need to make it nullable
or assign default value
, or delete all the existing records
to solve it.