Laravel hasMany detach

I am having a problem with Eloquent regarding deleting a child model: When this is done in process2() , I still have a remote model that is out of order.

Model

  namespace App\Models; use Illuminate\Database\Eloquent\Model; class Model1 extends Model { public function seasons() { return $this->hasMany('App\Models\Seasons', 'series_id', 'id'); } } 

Service

 class Process { public function process1($model1Instance) { for($model1Instance->seasons() as $season) { if(//whatever//) { $season->delete(); } } } public function process2($model1Instance) { for($model1Instance->seasons() as $season) { //At this point I still have the deleted instance } } } 

Using

 $proc = new Process(); ...... $proc->process1($model1Instance); $proc->process2($model1Instance); 

When process1() removes the model from the parent, how can I remove it in process2() ?

Tried / will try:

1.Method: $ Model1Instance-> seasons () → detachment ($ season); but got: Call to undefined method Illuminate\Database\Query\Builder::detach()

2. Another class I could make another simple class to store them, but I do not think that everything is in order, although I could set the filtered seasons, but I still have to use an instance of Model1:

 class Model1Copy { private $seasons; public function __construct($seasons) { $this->seasons = $seasons; } } 
  1. Fatal while trying:

    public function process1 ($ model1Instance) {

     for($model1Instance->seasons() as $season) { if(//whatever//) { $season->delete(); } else { $childs[]=$season; } } $model1Instance->seasons = $childs 

    }

  2. It would make my own repositories to skip the ORM behavior, but this is frustrating because I have to rewrite all requests in order to delete the instance ...

+9
source share
3 answers

$model->seasons() returns the relation, while $model->seasons returns the season collection associated with the model. Try the following.

 public function process1($model1Instance) { // Iterate over the collection for($model1Instance->seasons as $season) { if(condition) { $model1Instance->seasons()->detach($season); $season->delete(); } } $model1Instance->save(); } 

In addition, you repeat all the seasons of all models and delete seasons that satisfy certain conditions. It would not be more effective if you destroyed all the seasons. Something like the following:

 $seasons = Season::where(condition)->get(); Season::destroy($seasons); 
0
source

try it

 public function process1($model1Instance) { // Iterate over the collection for($model1Instance->seasons as $season) { if(condition) { $season->delete(); } } $model1Instance->save(); } 
0
source

To delete hasMany entries with a condition:

 $model1Instance->seasons()->where('condition', 'met')->delete(); 

To delete everything:

 $model1Instance->seasons()->delete(); 
0
source

All Articles