CakePHP hasOne/belongsTo model relationship

theraccoonbear picture theraccoonbear · Nov 23, 2011 · Viewed 9.4k times · Source

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?

Answer

brism picture brism · Nov 23, 2011

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.