Home > OS >  Integrity constraint violation. There is no Contradiction. Laravel
Integrity constraint violation. There is no Contradiction. Laravel

Time:04-06

How can I resolve this error? I cannot seem to find there is Integrity constraint violation.

Error :

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (kondate.created_kondates_foods, CONSTRAINT created_kondates_foods_food_id_foreign FOREIGN KEY (food_id) REFERENCES foods (id)) (SQL: insert into created_kondates_foods (created_kondate_id, food_id, updated_at, created_at) values (34, 6655, 2022-04-05 19:00:31, 2022-04-05 19:00:31)) in file /Users/Developments/kondate/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 669

My codes :

class CreatedKondate extends Model
{
    protected $connection = 'kondate';

    protected $table = 'created_kondates';

    protected $guarded = ['id'];

    public function foods()
    {
        return $this->belongsToMany('App\Models\Food', 'created_kondates_foods', 'created_kondate_id', 'food_id');
    }
}

a model of Intermediate table .

CreatedKondateFood

class CreatedKondateFood extends Model
{
    protected $connection = 'kondate';

    protected $table = 'created_kondates_foods';

    protected $guarded = ['id'];

}

Database output function

 $first_date = date("2022-04-01");
 $end_date = date("2022-04-t");

        for($i = $first_date; $i<=$end_date ;$i  )
        {
            $createdKondate = new CreatedKondate;
            $createdKondate->company_id = $company_id;
            $createdKondate->calendar_date = $i;
            $createdKondate->save();

        $createdKondateFood = new CreatedKondateFood;
        $createdKondateFood->created_kondate_id = $createdKondate->id;
        $createdKondateFood->food_id = '6655';
        $createdKondateFood->save();
        }
    }

enter image description here

CodePudding user response:

What if you replace

    $createdKondateFood->food_id = '6655';

by

    $createdKondateFood->food_id = 6655;

It may also comes from the fact that there's no item having its id set to 6655 in the food table

  • Related