Answer the question
In order to leave comments, you need to log in
How to delete a hasMany link?
I don’t understand a little how to remove the hasMany connection. I have a table branch and room. That is, one branch has several rooms. I tried to find it in the documentation, but so far I haven’t really found anything unless foreach goes through everything and deletes records.
That’s what the error is
"SQLSTATE[23503]: Foreign key violation: 7 ERROR: UPDATE or DELETE on table 'branch' violates foreign key constraint 'room_branch_id_foreign' on table 'room'
DETAIL: Key (id)=(4) is still referenced in table " room". (SQL: delete from "branch" where "id" = 4)"
public function destroy($id)
{
return Branch::destroy($id);
}
class Branch extends Model
{
protected $table = 'branch';
protected $dateFormat = 'U';
protected $fillable = ['name', 'city', 'street', 'build', 'appartament', 'phone', 'user_id'];
public function rooms()
{
return $this->hasMany('Growth\Room');
}
}
public function destroy($id)
{
$branch = Branch::find($id)->rooms();
$branch->delete();
return Branch::destroy($id);
}
Answer the question
In order to leave comments, you need to log in
You are sent a delete request, but deletion is not possible, because there are records in the database that refer to this foreign key.
You either need to first delete from the database the records that refer to the one being deleted, or designate the behavior in the database when such a record is deleted. For example, with on delete cascade, records referring to the one being deleted will be automatically deleted by the database itself.
Google mysql on delete
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question