Strange insert error..Integrity constraint violation

Published 4 months ago by Webiondev123

Ok, whenever I am trying to insert column 'to_' using eloquent it gives me error integrity constraint violation but when I insert using DB::table it inserts..why?



QLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`databasename`.`message`, CONSTRAINT `message_to__foreign` FOREIGN KEY (`to_`) REFERENCES `users` (`id`)) (SQL: insert into `message` (`from`, `updated_at`, `created_at`) values (2, 2018-02-21 07:29:05, 2018-02-21 07:29:05))




function insertThis($id){
  DB::table('message')->insert(array('from' => auth()->user()->id,'to_'=>$id, 'message' => 'sdvsdvsdv', 'date'=>date('Y-m-d'))); //ok


   $message->fill(['from'=>auth()->user()->id],
            ['to_'=>$id],
            ['message'=>'kkssd'],
            ['date'=>date('Y-m-d')]);


}

 if($message->save())
   //Redirect

$table->integer('to_')->unsigned();
 $table->foreign('to_')->references('id')->on('users');

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
class Message extends Model
{


    protected $table='message';
    protected $fillable = [
    'from', 'to_', 'message','date' 
    ];

   
}



```
Best Answer (As Selected By Webiondev123)
austenc

It's hard to tell from your example, but it looks like you're using fill and not calling save() afterwards. I would recommend using either create() or update()instead!

Additionally, you shouldn't need separate arrays. Combining those two ideas would give something like:

$message->create([
    'from' => auth()->user()->id,
    'to_' => $id
]);
edoc
edoc
4 months ago (67,040 XP)
$message->fill([
    'from '=> auth()->user()->id, 
    'to_'     => $id
])->save(),
biishmar

Would you please display the full error?

austenc

It's hard to tell from your example, but it looks like you're using fill and not calling save() afterwards. I would recommend using either create() or update()instead!

Additionally, you shouldn't need separate arrays. Combining those two ideas would give something like:

$message->create([
    'from' => auth()->user()->id,
    'to_' => $id
]);
Webiondev123

@austenc @biishmar @edoc Edited code

Webiondev123

@austenc putting all in one array works!

Please sign in or create an account to participate in this conversation.