Context: By registering a company, by being "attached" several clients to it and that same customer can be "attached" in other companies.
I have the following database structure:
Model "Client":
public function enterprises()
{
return $this->belongsToMany('App\Models\Enterprise', 'enterprise_client');
}
Model "Enterprise":
public function clients()
{
return $this->belongsToMany('App\Models\Client', 'enterprise_client');
}
Pivot "enterprise_client":
public function up()
{
Schema::create('enterprise_client', function (Blueprint $table) {
$table->increments('id');
$table->integer('enterprise_id')->unsigned();
$table->foreign('enterprise_id')->references('id')->on('enterprises')->onDelete('restrict');
$table->integer('client_id')->unsigned();
$table->foreign('client_id')->references('id')->on('clients')->onDelete('restrict');
$table->timestamps();
});
}
To save the data:
if (isset($dataRequest['clients'])) {
$enterprise->clients()->sync($dataRequest['clients']);
}
"$ dataRequest ['clients']" is an array of ID's. "isset ()" is to check if you have this array in the Request, because during the registration, filling in clients is not mandatory.
However, when trying to save the data, I get the error:
local.ERROR: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ('my_project'.'enterprise_client', CONSTRAINT 'enterprise_client_client_id_foreign' FOREIGN KEY ('client_id') REFERENCES 'clients' ('id')) in /home/Workspace/MyProject/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:142
Using attach()
instead of sync()
returns the same error.
What could be causing this?