0

I create a table- GAllERY_ID on POST. That is a foreign key nullable, and null as default. When I create a POST, if I don't set the GALLERY_ID, it will be null. But if I set the GALLERY_ID and reference on a GAllery, after if I try to make this NULL again (ON UPDATE ), I can´t.

I did like this the migration -

UP –

$table->integer(‘gallery_id’)->unsigned()->nullable()->default(null);

$table->foreign(‘gallery_id’)->references(‘id’)->on(‘photo_gallery’);

DOWN –

$table->dropForeign(‘posts_gallery_id_foreign’);

Have a look on the image of my DB on PHP MY ADMIN

If I go on PHP my admin I can update this value, just checking NULL on Gallery ID, BUT in my code on UPDATE, if I set like this -

$post->gallery_id      =  Null;

It will give this error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ...

Because I can't set null a foreign key to Update, just on a created method, if I don't set, it will be null, but if I set a value and after I try to change to NULL, I can't.

Some one can help me?

SurvivalMachine
  • 7,946
  • 15
  • 57
  • 87
murilo
  • 41
  • 5
  • Please try `$post->attributes['gallery_id'] = NULL;` – Ismail RBOUH Jul 11 '16 at 15:52
  • Hello my friend , Thanks for the fast answering . I tried this code on the controller , but its gives me an error - ErrorException in NoticiasController.php line 361: Indirect modification of overloaded property App\Post::$attributes has no effect I tried this code as well on the model like this - public function setGalleryIdAttribute(){ $this->attributes['gallery_id'] = NULL; } But it didnt make any difference , it still givng the same error , and It does not aloud to me to change to a Null value after I set a reference . – murilo Jul 11 '16 at 16:13
  • Okey! in your migration try: `$table->foreign(‘gallery_id’)->references(‘id’)->on(‘photo_gallery’)->onUpdate('cascade')->onDelete('SET NULL');`. You are welcome ;) – Ismail RBOUH Jul 11 '16 at 16:16
  • Is this on UP or on Down method ? – murilo Jul 11 '16 at 16:20
  • Rollback the migration then add it to UP the commit ;) – Ismail RBOUH Jul 11 '16 at 16:47
  • It is still giving the same error - SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ... – murilo Jul 11 '16 at 17:08
  • I tried on UP method - $table->foreign('gallery_id')->references('id')->on('photo_gallery')->onUpdate('cascade')->onDelete('SET NULL'); as well $table->foreign('gallery_id')->references('id')->on('photo_gallery')->onUpdate('cascade'|'restrict'|'set null'|'no action'); Ass well $table->foreign('gallery_id')->references('id')->on('photo_gallery')->onUpdate('set null')->change(); – murilo Jul 11 '16 at 17:15

0 Answers0