0
votes

i have reply_qs table and postqs table.Postqs_id is foreign key in reply_qs table.when i tried to save the reply_qs form data in database,its showed this error.

ERROR:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (fyp2.reply_qs, CONSTRAINT reply_qs_postqs_id_foreign FOREIGN KEY (postqs_id) REFERENCES postqs (id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into reply_qs (reply, updated_at, created_at) values (saann, 2017-09-22 15:35:03, 2017-09-22 15:35:03))

how i can solve it? and please explain why im getting this error.

reply_qs model :

 protected $table = 'reply_qs';
 protected $fillable = ['reply'];

 public function postqs(){
     return $this->hasMany('App\Postqs');
    }

postqs model :

  public function reply_qs(){
     return $this->hasMany('App\Reply_qs');
    }

store function:

  public function store(Request $request){
    $data = $request->all();
    $postqs=($request->id);
    $reply=Reply_qs::create($data);
    $reply->postqs($id); 
  }

migration:

   Schema::create('reply_qs', function (Blueprint $table) {
        $table->increments('id')->unique();
        $table->text('reply');
        $table->timestamps('date');
       });

   DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    Schema::table('reply_qs',function(Blueprint $table)
    {
     $table->integer('postqs_id')->unsigned();
     $table->foreign('postqs_id')->references('id')->on('postqs') -
     >onDelete('cascade')->onUpdate('cascade');
    });

    DB::statement('SET FOREIGN_KEY_CHECKS=1;');
1
Try to remove relations on your database. I mean constraints and references. Instead, try to handle those constraints and references in your code. - Morteza Rajabi

1 Answers

0
votes

Your relationships are not correct.

Your Reply_qs model should have this relationship with Postqs

public function postqs()
{
    return $this->belongsTo(Postqs::class);
}

Your store function does not look correct and should look something like this

public function store( Request $request )
{
   $reply = new Reply_qs();
   $reply->text = $request->get('text');
   $reply->postqs_id = $request->get('postqs_id');
   $reply->save();
}

In your store method, it looks like you are trying to associate the parent Postqs object with the Reply_qs.

You would do this like so

$reply->associate($post);

You need to pass the object and not the id

If you are still struggling with this double check your foreign keys are matching correctly, you may need to implement the association like so

public function postqs()
{
    return $this->belongsTo(Postqs::class, 'postqs_id', 'id);
}