Laravel有很多分离 [英] Laravel hasMany detach

查看:86
本文介绍了Laravel有很多分离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Eloquent有关删除子模型的问题: 在process2()中执行此操作后,我仍然删除了不正确的模型.

I am having an issue with Eloquent regarding removing child model: When this is executed in process2() I still have the deleted model which is not ok.

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

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

服务

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
        }
    }
}

用法

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

process1()从父级删除模型时,如何在process2()中删除它?

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

1.方法: $ model1Instance-> seasons()-> detach($ season); 但得到了:Call to undefined method Illuminate\Database\Query\Builder::detach()

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

2.另一堂课 我可以制作另一个简单的类来存储它们,但是我认为这没关系,尽管我可以设置过滤后的季节,但仍然必须使用Model1实例:

2.Another class I could make another simple class to store these but I do not think it is okay, although I could then set filtered seasons but still have to use Model1 instance:

class Model1Copy {
    private $seasons;
    public function __construct($seasons) {
        $this->seasons = $seasons;
    }
}

  1. 尝试时致命:

  1. Fatal when tried:

公共功能process1($ model1Instance){

public function process1($model1Instance) {

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

}

将创建自己的存储库以跳过ORM的行为,但这令人沮丧,因为我必须重写所有查询才能删除实例...

Would be to make my own repositories to skip the ORM`s behavior, but it is frustrating because I have to rewrite all queries just to remove an instance...

推荐答案

要删除具有条件的hasMany记录:

To delete hasMany records with condition:

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

要全部删除:

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

这篇关于Laravel有很多分离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆