CakePHP hasOne/belongsTo model relationship
Asked Answered
B

1

4

I have a few models I'm trying to relate.

One model is Item, one is Slide, and another is Asset.

Items have multiple slides beneath them. Assets are basically files that have been uploaded (images, mp3s, etc) and slides are where assets are displayed. Each slide has one asset, but a given asset might belong to multiple slides. A slide has an asset_id field defined.

I currently have the models defined as:

Slide

class Slide extends AppModel {
    var $name = 'Slide';

    var $order = array("Slide.order" => "asc");

    var $belongsTo = 'Item';

    var $hasOne = array(
        'Asset' => array(
          'className' => 'Asset',
            'foreignKey' => 'id',
            'dependent' => false
        )
    );

} // Slide class

Asset

class Asset extends AppModel {
    var $name = 'Asset';

    var $displayField = 'name';

    var $belongsTo= array(
        'Assetdir' => array(
            'className' => 'Assetdir',
            'foreignKey' => 'assetdir_id'
        ),
        'Slide' => array(
            'className' => 'Slide',
            'foreignKey' => 'id'
        )
    );  
} // Asset class

When I load a slide, I'm seeing its parent element, Item, come through in the returned data, but the associated asset is not. What am I doing wrong here?

Baur answered 23/11, 2011 at 21:56 Comment(0)
O
4

Actually I think this is a one-to-many relationship between Slide and Asset. From the Model associations page: belongsTo: the current model contains the foreign key. So, any model that has a foreign key to another one belongs to the other one.

So the way I see it:

Item:

  • hasMany Slide

Slide:

  • belongsTo Item (with item_id)
  • belongsTo Asset (with asset_id)

Asset:

  • hasMany Slide

For retrieving the associated models you want, I'd suggest looking at the Containable behavior.

Osullivan answered 23/11, 2011 at 22:20 Comment(3)
Excellent, thank you. I'd been coming at this from the wrong direction. I guess then I'm wondering, what would be a relationship where hasOne would be appropriate?Baur
hasOne is frequently for breaking up data into multiple tables. For example, a User has one Profile. The data could all be placed on the User model, but breaking it up allows you to make functionality more granular.Deloris
hasOne is better suited to one-to-one relationships. The example they give on that associations page is a User and their Profile. A User hasOne Profile, and the Profile belongsTo User (because it has the foreign key user_id).Osullivan

© 2022 - 2024 — McMap. All rights reserved.