Laravel有许多分离

时间:2015-09-18 23:38:07

标签: php eloquent laravel-5.1

我对Eloquent有关删除子模型的问题: 当在process2()中执行此操作时,我仍然有删除的模型,这是不正确的。

模型

    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()中移除模型?

尝试/将尝试:

1.Method:     $ model1Instance->季节() - >分离($季节); 但得到了:Call to undefined method Illuminate\Database\Query\Builder::detach()

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

class Model1Copy {
    private $seasons;
    public function __construct($seasons) {
        $this->seasons = $seasons;
    }
}
  1. 尝试时致命:

    public function process1($ model1Instance){

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

    }

  2. 将使我自己的存储库跳过ORM的行为,但它令人沮丧,因为我必须重写所有查询只是为了删除一个实例......

3 个答案:

答案 0 :(得分:0)

$model->seasons()返回关系,而$model->seasons返回映射到模型的季节集合。请尝试以下方法。

public function process1($model1Instance) {

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

    $model1Instance->save();
}

此外,您正在迭代所有模型的所有季节,并删除满足某些条件的季节。如果你一次性摧毁所有季节,那会不会更有效率。如下所示:

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

答案 1 :(得分:0)

尝试一下

public function process1($model1Instance) {

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

    $model1Instance->save();
}

答案 2 :(得分:0)

要删除hasMany条记录,条件如下:

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

要全部删除:

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