php Laravel 模型返回“未定义的属性:stdClass::$name”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25417312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel model returns "Undefined property: stdClass::$name"
提问by TorrBallen
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;
}
}
And when I call it:
当我调用它时:
$food = new Food($id);
var_dump($food->name()); exit;
Returns:
返回:
Undefined property: stdClass::$name
回答by monque
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
.
根据您的代码,DB::select
将返回一个包含多个对象(可能不止一个)的数组,然后您将其分配给$this->food
.
Remember, the $this->food
looks like
记住,$this->food
看起来像
Array (
[0] => stdClass Object (
[name] => 'Beef'
)
)
Actually, $this->food->name
is trying to access an undefined property.
实际上,$this->food->name
正在尝试访问未定义的属性。
Solution 1:
解决方案1:
You should use $this->food[0]->name
to access it.
您应该使用$this->food[0]->name
它来访问它。
Although it looks weird, but it works.
虽然看起来很奇怪,但它确实有效。
Solution 2:
解决方案2:
Why not call Food::find($id)
to fetch the object instead of $food = new food($id)
为什么不调用Food::find($id)
来获取对象而不是$food = new food($id)
You can learn more by reading this http://laravel.com/docs/eloquent
您可以通过阅读此http://laravel.com/docs/eloquent了解更多信息