我一直试图让我的类模型正常工作,但它不断返回此错误。
该模型看起来像:
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
.
请记住,$this->food
好像
Array (
[0] => stdClass Object (
[name] => 'Beef'
)
)
其实,
$this->food->name
正在尝试访问未定义的属性。解决方案 1 :
您应该使用
$this->food[0]->name
访问它。虽然看起来很奇怪,但它确实有效。
解决方案 2 :
为什么不打电话
Food::find($id)
获取对象而不是 $food = new food($id)
您可以通过阅读此内容了解更多信息 http://laravel.com/docs/eloquent
关于php - Laravel 模型返回 "Undefined property: stdClass::$name",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25417312/