f.gruber
(Ferdinand)
January 8, 2015, 12:59pm
1
Please help me, I am still a Yii beginner
May be I don’t understand something with lazy loading.
I have a model folders with relation. There is a foreign key User_Id . It is related to the primaryKey of the User Table: Id .
public function relations() {
return array(
'User'=>array(self::BELONGS_TO, 'User', 'User_Id')
Now I want to display data of an existing field of the related User model:
echo "User: ".$model->User->Name;
I get the error
Trying to get property of non-object.
$model->User seems to be NULL. I don’t understand, why. It is the first time, I use lazy loading …
Of course I can access the attributes of the folders model, for instance:
echo "Folder Title: ".$model->title;
In
echo "User: ".$model->User->Name;
$model is almost a model of User, so you haven’t to type $model->User to get User, but you have user in $model.
f.gruber
(Ferdinand)
January 8, 2015, 1:22pm
3
I don’t understand that right
I want to display User->name in the folders form. In my example the variable $model contains the activeRecord object of the folders model.
This is the controller code of the folders controller:
public function actionUpdate() {
$model=$this->loadModel($id);
if ( isset($_POST['folders']) ) {
...
} else {
$this->render('update',array(
'model'=>$model,
...
In update.php the variable $model is passed to _form.php. There is nothing special.
Please can you give me a hint, how to display attibutes of the related model User (using the lazy loading method of Yii).
Shnoulle
(Courriel)
January 8, 2015, 1:37pm
4
f.gruber
(Ferdinand)
January 8, 2015, 1:48pm
5
The documentation of the with method says:
with(): Specifies which related objects should be eagerly loaded.
But I wanted to try lazy loading . It is my first attempt with lazy loading …
What goes wrong in my example?
f.gruber
(Ferdinand)
January 8, 2015, 3:12pm
6
I found the reason of the problem:
In my model I had a public variable named $User . I used this variable before I defined the relation to the model User and I forgot to delete this variable.
Now the expression $model->User refered to the variable $User and not to the relation "User" . Therefore $model->User was empty because it did not refer to the relation with the same name.
I apologize for this mistake. Thank you for trying to help me.