php - CakePHP Entity contain without foreign key -


i have entity villa, , want entity contain other villas have same 'complex' (varchar(255)).

class villastable extends table {      /**      * initialize method      *      * @param array $config configuration table.      * @return void      */     public function initialize(array $config)     {         $this->table('villas');         $this->displayfield('name');         $this->primarykey('id');          $this->hasmany('complexs', [             'classname' => 'villas',             'foreignkey' => false,             'propertyname' => 'complexs',             'conditions' => ['complexs.complex' => 'villas.complex']         ]);     } } ?> 

i don't know if it's possible. don't want add find in each function need entity. make function in entity uses new field. ``

despite fact using varchar(255) foreign key highly inefficient and/or require huge indices, guess option defines foreign key of other table come in handy here, similar targetforeignkey belongstomany associations. may want suggest enhancement.

result formatters

currently doesn't seem possible out of box using associations, you'd have select , inject associated records yourself, example in result formatter.

$villas     ->find()     ->formatresults(function($results) {         /* @var $results \cake\datasource\resultsetinterface|\cake\collection\collection */          // extract custom foreign keys results         $keys = array_unique($results->extract('complex')->toarray());          // find associated rows using extracted foreign keys         $villas = \cake\orm\tableregistry::get('villas')             ->find()             ->where(['complex in' => $keys])             ->all();          // inject associated records results         return $results->map(function ($row) use ($villas) {             if (isset($row['complex'])) {                 // filters associated records based on custom foreign keys                 // , adds them property on row/entity                 $row['complexs'] = $villas->filter(function ($value, $key) use ($row) {                     return                         $value['complex'] === $row['complex'] &&                         $value['id'] !== $row['id'];                 })                 ->toarray(false);             }             return $row;         });     }); 

this fetch associated rows afterwards using custom foreign keys, , inject results, you'd end associated records on entities.

see cookbook > database access & orm > query builder > adding calculated fields

there might other options, example using custom eager loader collects necessary keys, combined custom association class uses proper key stitching results together, see


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -