【问题标题】:可以检查所有 foreach 循环结果的条件是否为真?
【发布时间】:2022-01-23 00:05:36
【问题描述】:

如果foreach 循环内给出的if 条件对于foreach 循环的所有迭代都是true,我想返回错误消息。意味着,只有当$id 存在于所有 foreach 循环迭代中的CoursePublishChaptercontent 中(不仅仅是在特定迭代中),我才需要 break 。我该怎么做?

foreach($chapterContentId as $id){
                    if(CoursePublishChaptercontent::where('course_chapter_content_id',$id)->exists()){
                        return response()->json([
                            'message' => "Course publish failed",
                            'statusCode' => 400,
                            'status' => 'Failed',
                            'errorMessages' =>  ['Availble course chapters and contents are already published']
                        ], 400);
                    }
                  }

【问题讨论】:

    标签: php laravel eloquent foreach laravel-8


    【解决方案1】:

    您可以使用every收集方法:

    $val = collect($chapterContentId)->every(function($id) {
      return CoursePublishChaptercontent::where('course_chapter_content_id',$id)->exists();
    }):
    
    if ($val) {
      // all exist
    } else {
      // all don't exist
    }
    

    【讨论】:

    • 如果表中存在第一个迭代中的数据,则返回true;如果表中不存在第一个迭代中的数据,即使false 也返回。只有当所有迭代中的数据都存在于表中时,我才想返回true
    【解决方案2】:

    或者,您也可以根本不执行循环并将其减少到 1 个单个查询,而不是执行 X 个查询,因为迭代:

    // make sure there are only unique values in the list
    // if array
    $chapterContentIds = array_unique($chapterContentIds);
    // if collection
    $chapterContentIds = $chapterContentIds->unique();
    
    $allExist = CoursePublishChaptercontent::whereIn('course_chapter_content_id', $chapterContentIds)
        ->count() == count($chapterContentIds);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      相关资源
      最近更新 更多