根据Doctrine manual我应该能够使用箭头符号($record->myField
)或数组符号($record['myField']
)引用模型的属性,只要模型是派生自Record
类。
我使用Doctrine从我的数据库生成我的模型,所以我有一个(生成的)Recipe
类,它扩展了BaseRecipe
类,扩展了Doctrine_Record
。实例化Recipe
对象后,我可以使用数组表示法来访问其值,但使用箭头表示法只返回空值。我错过了什么?
Doctrine生成的BaseRecipe类有两种方法:
public function setTableDefinition()
{
$this->setTableName('rcp_recipe');
$this->hasColumn('recipe_id', 'integer', 4, array(
'type' => 'integer',
'fixed' => 0,
'unsigned' => false,
'primary' => true,
'autoincrement' => true,
'length' => '4',
));
...
}
public function setUp()
{
parent::setUp();
$this->hasMany('RcpTime', array(
'local' => 'time_id',
'foreign' => 'time_id'));
...
}
以下是我尝试使用它的方法:
$newRecipes = RecipeService::getLatestRecipes();
foreach ($newRecipes as $recipe)
{
echo($recipe['title']); // prints the expected value
echo($recipe->title); // prints empty string
}
这是我的getLatestRecipes
方法:
static function getLatestRecipes() {
$q = Doctrine_Query::create()
->from('Recipe')
->orderBy('recipe_id desc')
->limit(5);
return $q->fetchArray();
}
答案 0 :(得分:2)
return $q->fetchArray();
有问题;)
将其更改为
static function getLatestRecipes() {
$q = Doctrine_Query::create()
->from('Recipe')
->orderBy('recipe_id desc')
->limit(5);
return $q->execute();
}
你会得到一个物体,它可以让你使用'箭头'。
使用[]从数组中获取属性,并使用 - >从对象获取属性。由于您的方法返回一个数组 - >不起作用。
您应该收到错误消息。 (“试图从非对象获取属性”或类似的东西)
在您还在开发时设置error_reporting(E_ALL)
。