2
我試圖輸出Yii2中的相關數據。我的輸出代碼看起來像這樣(像我這樣做Yii中1):Yii2輸出關係數據
foreach ($model->comments as $key => $comment) {
echo $comment->title;
}
,但我得到的錯誤tying to get property on a non-object
的$model->comments
的var_dump顯示陣列,是什麼樣子的:的
array (size=1)
0 =>
object(common\models\Comment)[74]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=5)
'id' => int 1
'title' => string 'testComment' (length=11)
'body' => string 'body' (length=4)
'post_id' => int 1
'user_id' => int 1
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=5)
'id' => int 1
'title' => string 'testComment' (length=11)
'body' => string 'body' (length=4)
'post_id' => int 1
'user_id' => int 1
private '_related' (yii\db\BaseActiveRecord) =>
array (size=0)
empty
的var_dump $model->getComments()
返回ActiveQuery對象:
object(yii\db\ActiveQuery)[67]
public 'sql' => null
public 'on' => null
public 'joinWith' => null
public 'select' => null
public 'selectOption' => null
public 'distinct' => null
public 'from' => null
public 'groupBy' => null
public 'join' => null
public 'having' => null
public 'union' => null
public 'params' =>
array (size=0)
empty
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
empty
public 'where' => null
public 'limit' => null
public 'offset' => null
public 'orderBy' => null
public 'indexBy' => null
public 'modelClass' => string 'common\models\Comment' (length=21)
public 'with' => null
public 'asArray' => null
public 'multiple' => boolean true
public 'primaryModel' =>
object(common\models\Post)[65]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=5)
'id' => int 1
'header' => string 'ds' (length=2)
'content' => string 'dsad' (length=4)
'created' => string '0000-00-00' (length=10)
'status' => int 1
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=5)
'id' => int 1
'header' => string 'ds' (length=2)
'content' => string 'dsad' (length=4)
'created' => string '0000-00-00' (length=10)
'status' => int 1
private '_related' (yii\db\BaseActiveRecord) =>
array (size=0)
empty
private '_errors' (yii\base\Model) => null
private '_validators' (yii\base\Model) => null
private '_scenario' (yii\base\Model) => string 'default' (length=7)
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
empty
public 'link' =>
array (size=1)
'post_id' => string 'id' (length=2)
public 'via' => null
public 'inverseOf' => null
我看到我在這兩種情況下的數據,但我怎樣才能從這種結構收到呢? (和什麼方式$ model-> getComments()或$ model->評論是賴特?)
你能做一個$ comment的var_dump嗎? – Barry 2014-10-19 15:42:18
您可以使用$ model-> comments或$ model-> getComments() - > All()。 – Barry 2014-10-19 15:46:43