문제

I have three tables, table1, table2, and table3. table1 is one-to-many to table2 and table2 is one-to-many to table3.

I want to invoke Table1::find($id)::delete() and have all the rows from table2 and table3 deleted as well.

I added the following to my tables:

Table1

public function delete()
{
    $this->table2()->delete();
    return parent::delete();
}

Table2

public function delete()
{
    $this->table3()->delete();
    return parent::delete();
}

However, my rows from table3 are not deleted. Table3's rows get deleted if I manually call the delete function from the model table2. The way I have written the code, shouldn't the delete() function from table2 be called when table1 calls it?

도움이 되었습니까?

해결책

You can't call delete() on the collection, neither load far related collection on the query builder, to remove related models, so what you need is this:

// Table1 model
public function delete()
{
  $this->table2->each(function ($model2) {
    $model2->table3()->delete();
  });

  $this->table2()->delete();
  return parent::delete();
}

다른 팁

I think this will delete sequentially all related ones:

// Table1
public function delete()
{
    $this->table2()->delete();
    $this->table2()->table3()->delete();
    return parent::delete();
}

I found this from laracasts and found it useful for me. Let me paste the answer here: So I have two models - User and Property User.php

public function properties()
    {
        return $this->hasMany('App\Models\Property');
    }

Property.php

public function user()
    {
        return $this->belongsTo('App\User');
    }

Thus, if I want to delete a particular user, and of course, I don't want any his properties to be retained in the database:

public function destroy($id)
    {
        $user = User::findOrFail($id);

        $user->properties()->delete();

        $user->delete();

        return [
            'message' => 'Delete Complete!'
        ];
    }

I hope you or anyone else finds this useful! Regards :)

Source: https://laracasts.com/discuss/channels/eloquent/laravel-delete-model-with-all-relations

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top