0
Context: When registering a company, by being "attached" several customers 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 Request, because during registration, client completion is not required.
However, when trying to save the data, I returned 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?
I already have this 3 pivot table in my model, I said this in my question.
– Matheus de Melo .F
@Matheusdemelo. F updated my response with tested code that works. I hope it helps.
– Ricardo Santos