Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP - Extended Model Associations

I've very curious about what I'm missing. Only an example will help explain but here's the sentence question first: Inventory and InventoryCategory - both have Image associations. When I view a single InventoryCategory and the related Inventory I would like both Image associations. Currently I'm only returned the InventoryCategory->Image. No images are returned for the Inventory items. This is what I have in the models:

Inventory:
 public $belongsTo = 
  array(
     'User' 
   , 'InventoryCategory' 
   , 
  );

 public $hasMany = 
  array(
     'Image' => array
    (
       'className' => 'Media.MediaImage' 
     , 'foreignKey' => 'foreign_key' 
     , 'conditions' => array(
          'Image.model' => 'Inventory' 
        , 'Image.group' => 'Image' 
        , 
       )
     , 'dependent' => true 
     , 'order' => 'Image.rank ASC, Image.id ASC' 
    ) 
   , 
  );

 public function containedModels() 
 {
  $contain = array(
      'Image' 
    , 'User' 
    , 'InventoryCategory' 
    , 
  );
  return $contain;
 }
InventoryCategory
 public $hasOne = 
  array(
    'Image' => array
    (
       'className' => 'Media.MediaImage' 
     , 'foreignKey' => 'foreign_key' 
     , 'conditions' => array(
          'Image.model' => 'InventoryCategory' 
        , 'Image.group' => 'Image' 
        , 
       )
     , 'dependent' => true 
     , 
    ) 
   ,   
  );

 public $hasMany = 
  array(
     'Inventory' 
   , 
  );

 public function containedModels() 
 {
  $contain = array(
      'Image' 
    , 'Inventory' 
    , 
  );
  return $contain;
 }
like image 600
radarhill Avatar asked Apr 21 '26 02:04

radarhill


1 Answers

If you're trying to pull back both Image relationships within a single find(), then you're going to have problems as CakePHP is only going to select one of those same named relationships, it needs to disambiguate somehow and will either throw an error or just select the first found relationship (which seems to be what you're seeing).

I'd recommend calling the relationships to Media.MediaImage something unique in both cases, e.g. InventoryImage and InventoryCategoryImage rather than just Image.

like image 166
ianmjones Avatar answered Apr 29 '26 11:04

ianmjones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!