dr5648 2018-05-18 16:24
浏览 43
已采纳

Laravel 5.4 eloquent拥有许多和随后的PHP来检查批准状态

I have two models, Email and EmailReview. Email hasMany EmailReviews. This query:

$data = Email::with('emailReviews')->where('created_by', '=', $personId)->get();

returns a collection of a specific person's emails that have a review_group_type of either approval or feedback and a relationship of email_reviews that have an approved property of either true, false or null. I'm looking for the cleanest way to check if the email is an approval email and all of the reviews in the collection have their approved column set to true in order to set an approval status for each email i.e., $email->approvalStatus. Some emails will also not have reviews yet, so I'll need to check for that. Something along these lines, but it's clearly getting ugly and I'm having a hard time getting my end result:

if ($data->review_group_type === 'approval') {
        foreach($data as $email) {
            if (!is_null($email->email_reviews)) 
            foreach($email->email_reviews as $review) {

            }
        }
    }
  • 写回答

2条回答 默认 最新

  • dqrnsg6439 2018-05-18 16:57
    关注

    Building on @Salama96 response and going a little bit further, you can do this:

    $data = Email::with('emailReviews')
            ->where(['created_by'=>$personId,'review_group_type'=>'approval'])
            ->has('emailReviews')
            ->get()
            ->map(function ($email){
               // Here, you check if all the emailReviews are 'true'
               $reviewsStatus = $email->emailReviews->pluck('approved')->unique();
               if ($reviewsStatus->count() == 1 AND $reviewsStatus->first())
               {
                   $email->approvalStatus = true;
               }
    
               return $email;
            });
        }
    

    PS: Haven't test it properly, but it should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀