尝试使用Carbon删除数据库中具有特定查询的所有条目

问题描述 投票:0回答:1

我想要实现的是我想从我的桌子上删除17岁或以下未成年人的条目。而且我想删除父表。

所以这在我的模型中

// Define the "age" property accessor.
public function getAgeAttribute()
{
    return now()->diffInYears($this->birthdate);
}

这是我的控制器,

public function removeApplicanWhoAreNotAdults()
{
    $date = Carbon::createFromDate(2001, 01, 01);
    $todaysDate = Carbon::today();

    $lastDay = $date->copy()->endOfYear();

    $applicants = Applicant::whereBetween("birthdate", [$lastDay, $todaysDate])->get();

    $applicants->each(function ($item, $key) {

    });
}

我的控制器上的代码是否足以解决我正在尝试解决的问题以及如何查询年龄低于17岁的申请人,例如当我的年龄在我的数据库中为空时

laravel laravel-5.5 php-carbon
1个回答
0
投票
Solution 1:
       $applicant = Applicant::get();
              foreach ($applicant as $key => $value) {
                  $year = now()->diffInYears($value->birthdate);

                  if($year > 17){
                      Applicant::where('id', $value->id)->delete();
                  }
             }

第二种方法首先是你必须创建一个命令,你可以创建适当的编程和好方法。

按照这个例子

https://itsolutionstuff.com/post/example-of-cron-job-in-laravel-5example.html

将上面的代码放在handel()方法中

        public function handle()
        {
          $applicant = Applicant::get();
          foreach ($applicant as $key => $value) {
              $year = now()->diffInYears($value->birthdate);

              if($year > 17){
                  Applicant::where('id', $value->id)->delete();
              }
          }
        }
© www.soinside.com 2019 - 2024. All rights reserved.