循环函数中的处理程序空值(Foreach)Laravel

时间:2019-02-18 09:15:02

标签: php laravel loops foreach

我正在尝试在第一行years表(字段:colom_year)中获取所有值,并将字段year_start放在researches表中。所以我用这个:

use App/Research;
use App/Year;

public function updateDatabaseYearStartResearch()
{
    $researchs = Research::all();
    foreach($researchs as $r)
    {
            $yearNew = Year::where('research_id', $r->id) != null ? Year::where('research_id', $r->id)->first()->colom_year : 0;
            //dd($yearNew);
            $Riset = Research::find($r->id);
            $Riset->year_start =  $yearNew ;
            $Riset->save();
    }
}

当我dd($yearNew)获得价值时,我想我会使用真正的查询。但是,当我评论dd($yearNew)以运行我的函数时,会出现如下错误:

  

试图获取非对象的属性“ colom_year”

我认为这是错误的,因为null表中有years值,因此我使用此查询来处理错误:           $yearNew = Year::where('research_id', $r->id) != null ? Year::where('research_id', $r->id)->first()->colom_year : 0;

但是我得到同样的错误。如何解决该错误?

3 个答案:

答案 0 :(得分:1)

<?php 

$year = Year::where('research_id', $r->id)->first();

$yearNew = $year ? $year->colom_year ?? 0 : 0;
  • 以上将检查$ year是否包含一个值,如果其空值,则分配0
  • 如果$year是具有数据的Year的有效实例,但不包含列colom_year,则再次分配0

答案 1 :(得分:0)

Year::where('research_id', $r->id)Builder的实例,不是查询本身的结果,因此它不会为null。您想做的是:

$years = Year::where('research_id', $r->id)->get();
$yearNew = $years->isEmpty() ? 0 : $years->first()->colom_year;

答案 2 :(得分:0)

相反,您应该使用instanceof来检查Year是否为有效对象:

use App/Research;
use App/Year;

public function updateDatabaseYearStartResearch()
{
    $researchs = Research::all();
    foreach ($researchs as $r)
    {
        $yearNew = 0;
        $yearModel = Year::where('research_id', $r->id)->first();
        if($yearModel instanceof Year && isset($yearModel->colom_year)){
            $yearNew = $yearModel->colom_year;
        }
        //dd($yearNew);
        $Riset = Research::find($r->id);
        $Riset->year_start = $yearNew;
        $Riset->save();
    }
}