我正在尝试在第一行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;
但是我得到同样的错误。如何解决该错误?
答案 0 :(得分:1)
<?php
$year = Year::where('research_id', $r->id)->first();
$yearNew = $year ? $year->colom_year ?? 0 : 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();
}
}