我遇到了一个小问题,由于某种原因,我无法从关系模型中访问我的属性。
我一直收到同样的错误,'未定义属性:Illuminate \ Database \ Eloquent \ Collection :: $ season'
我一整天都在盯着这个,但我找不到解决办法。
<?php namespace App\Http\Controllers;
use App\Show;
use App\Episode;
class TestController extends Controller {
public function test(){
$shows = Show::where('active',1)->get();
foreach ($shows as $show) {
if($show->active == 1 && $show->airday == date('N'))
{
echo 'test';
$episode = $show->episodes()->orderBy('id', 'desc')->take(1)->get();
\Debugbar::info($episode);
//this is the line where he gives me
echo('New episodes avaible, Season '.$episode->season.' Episode '.$episode->episode.' From '.$show->name);
//end error
}
}
}
}
?>
虽然如果我打印出$ episode变量,我可以清楚地看到我想要访问的属性。
Illuminate\Database\Eloquent\Collection {#150
#items: array:1 [
0 => App\Episode {#241
#table: "episodes"
+timestamps: true
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
#attributes: array:6 [
"id" => "6"
"show_id" => "6"
"season" => "3"
"episode" => "15"
"created_at" => "2016-02-07 11:45:53"
"updated_at" => "2016-02-07 11:45:53"
]
#original: array:6 [
"id" => "6"
"show_id" => "6"
"season" => "3"
"episode" => "15"
"created_at" => "2016-02-07 11:45:53"
"updated_at" => "2016-02-07 11:45:53"
]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [
0 => "*"
]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
]
目前我对这段代码有什么不妥之处。 我希望有人能指出我正确的方向。
答案 0 :(得分:2)
当你致电->take(1)->get()
时,你告诉Eloquent(建造者,真的)给你一个Collection
对象,其中包含1个项目。
因此,当您尝试访问$season
属性时,您实际上是尝试在Collection对象上访问它,而不是您认为的模型。
你可以做几件事:
->take(1)->get()
来电替换为->first()
,$episode
变量视为一个集合,并通过访问$episode[0]
,first
变量($episode
)上致电$episode = $episode->first()
以获取其中的第一个模型对象。