我一直试图让我的类模型工作,但它一直返回这个错误。
模型如下:
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了解更多信息