如何使用休息或继续使用Laravel Eloquent Collection的每种方法?

2022-08-30 11:06:46

如何使用休息或继续使用Laravel Eloquent Collection的每个方法。我的代码是这样的:

$objectives->each(function($objective) {
        Collection::make($objective)->each(function($action) {
            Collection::make($action)->each(function($success_indicator) {
                Collection::make($success_indicator)->each(function($success_indicator) {
                    echo 'hi';
                    continue;
                });
            });
        });
    });

答案 1

我们可以返回 的 true/false ,对于truecontinuefalsebreak

继续:

collect([1,2,3,4])->each(function ($item){
            if ($item === 2) {
                return true;
            }
            echo $item;
});

输出: 1 3 4

破:

collect([1,2,3,4])->each(function ($item){
            if ($item === 2) {
                return false;
            }
            echo $item;
});

输出:1


答案 2

到 ,刚好脱离内部函数。到,嗯..continuereturnbreak

如果您使用的是Laravel 5.1 +,则可以返回以打破循环:false

$objectives->each(function($objective) {
    collect($objective)->each(function($action) {
        collect($action)->each(function($success_indicator) {
            collect($success_indicator)->each(function($success_indicator) {
                if ($condition) return false;
            });
        });
    });
});

对于较旧版本的Laravel,请使用常规循环:foreach

$objectives->each(function($objective) {
    foreach ($objective as $action) {
        foreach ($action as $success_indicators) {
            foreach ($success_indicators as $success_indicator) {
                echo 'hi';
                break;
            }
        }
    }
});

推荐