One to many

Hello, another new Yii user here.

I have read through most of the tutorials and have prior experience with other PHP-based frameworks such as CakePHP. I am working on a small simple application in an effort to better understand the Yii framework.

My application is rather simple thus far. I have Users which have one-to-many Listings. My model relations were not auto-generated by the Gii tool likely because I do not have foreign keys defined within my DB structure (MyISAM tables). I manually modified the relations as instructed by the documentation.

Within my database, I have data populated with one User and one Listing belonging to that User. The problem is that when I run a print_r to see what data my User has, the core User data is there but the Listing isn’t. Am I missing something?

User relations…

return array(

‘listings’ => array(self::HAS_MANY, ‘Listing’, ‘id’)

);

Listing relations…

return array(

‘owner’ => array(self::BELONGS_TO, ‘User’, ‘id’)

);

Thanks in advance.

You should specify FK in the relationship, not PK. You don’t have to add both relationships unless you plan to use them both ways.

/Tommy

I’ve removed the second relationship, and modified the User relationship from the PK to FK.

return array(

‘listings’ => array(self::HAS_MANY, ‘Listing’, ‘userID’)

);

My tables PK/FK’s are as follows

tbl_users

-id

tbl_listings

-id

-userID

Still no luck.

Start with this




//$models = User::model()->findAll();  // lazy loading

$models = User::model()->with('listings')->findAll(); // eager loading


foreach ($models as $model)

{

  echo 'user: '.$model->id.'<br/>';

  foreach ($model->listings as $listing)

    echo 'listing: '.$listing->id.'<br/>';

}



/Tommy

Ah, my fault I suppose. I’ve been using too much CakePHP and just assumed eager loading was the default. Thanks Tommy!

As a brand new yii user who has been knocking his head out trying to figure this out, let me ask what seems to be an obvious question to most people: where would you "start with this"? I.e. where would this code go?

As I go through the documentation, the one thing that seems to be missing is where you would but a code snippet like this. In the controller, in a given view (given the <br/>)?

this all goes to controller because this is oversimplification.

In real world application you pass the model to view and do the foreach part there.