R
R
Ruslan Absalyamov2018-04-29 17:55:03
Laravel
Ruslan Absalyamov, 2018-04-29 17:55:03

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)"

In the controller
public function destroy($id)
    {
        return Branch::destroy($id);
    }

In the model
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');
    }
}

There is, of course, such an example
public function destroy($id)
    {
        $branch = Branch::find($id)->rooms();
        $branch->delete();
        return Branch::destroy($id);
    }

Or am I misunderstanding in deleting related tables?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yan-s, 2018-04-29
@rusline18

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 question

Ask a Question

731 491 924 answers to any question