Laravel模型返回“未定义的属性:stdClass :: $ name" [英] Laravel model returns "Undefined property: stdClass::$name"
问题描述
我一直在尝试使我的类模型正常工作,但它总是返回此错误.
该模型如下所示:
I keep trying to get my class model to work but it keeps returning this error.
The model looks like:
class Food
{
protected $id;
public function __construct($id)
{
$results = DB::select('select * from food where id = ?', array($id));
if ( empty($results) )
{
throw new Exception('Food do not exsist.');
} else {
$this->food = (object) $results;
}
}
public function name()
{
return $this->food->name;
}
}
当我称呼它时:
$food = new Food($id);
var_dump($food->name()); exit;
返回:
Undefined property: stdClass::$name
推荐答案
根据您的代码,DB::select
将返回一个包含多个对象(可能多个)的数组,然后将其分配给$this->food
Base on your code, DB::select
will return an array which contains several objects (may be more than one), and then you assign it to $this->food
.
请记住,$this->food
看起来像
Array (
[0] => stdClass Object (
[name] => 'Beef'
)
)
实际上,$this->food->name
试图访问未定义的属性.
Actually, $this->food->name
is trying to access an undefined property.
解决方案1 :
您应该使用$this->food[0]->name
进行访问.
虽然看起来很怪异,但是可以正常工作.
Although it looks weird, but it works.
解决方案2 :
为什么不调用Food::find($id)
而不是$food = new food($id)
您可以通过阅读以下内容进一步了解 http://laravel.com/docs/eloquent
You can learn more by reading this http://laravel.com/docs/eloquent
这篇关于Laravel模型返回“未定义的属性:stdClass :: $ name"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!