CakePHP hasOne/belongsTo model relationship

夙愿已清 提交于 2019-12-06 05:37:07

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8249612/cakephp-hasone-belongsto-model-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!