Example #1
0
 /**
  * For each $item of the current collection find corresponging $other from $what collection,
  * which have $cond_field equal to $item[$check_field]
  * and append them to $item[$res_field] as a new collection.
  * If $extract_field argument is specified, $other[$extract_field] is used instead if $other
  * @param Collection $what
  * @param string $cond_field
  * @param string $res_field
  * @param string $check_field
  * @param string $extract_field
  * @return \Floxim\Floxim\System\Collection
  */
 public function attachMany(Collection $what, $cond_field, $res_field, $check_field = 'id', $extract_field = null, $extract_real_field = null)
 {
     // what = [post1,post2]
     // this = [user1, user2]
     // cond_field = 'author'
     // res_field = 'posts'
     $res_index = array();
     foreach ($what as $what_item) {
         $index_key = $what_item[$cond_field];
         if (!isset($res_index[$index_key])) {
             if ($extract_field) {
                 $new_collection = fx::collection();
                 $new_collection->is_sortable = $what->is_sortable;
                 $linkers = $what->fork();
                 $linkers->addFilter($cond_field, $index_key);
                 if ($extract_real_field) {
                     $linkers->linkedBy = $extract_real_field;
                 }
                 $new_collection->linkers = $linkers;
                 if (isset($what->relFinders) && isset($what->relFinders[$extract_field])) {
                     $new_collection->finder = $what->relFinders[$extract_field];
                 }
             } else {
                 $new_collection = $what->fork();
                 $new_collection->addFilter($cond_field, $index_key);
             }
             $res_index[$index_key] = $new_collection;
         }
         if (!$extract_field) {
             $res_index[$index_key][] = $what_item;
         } else {
             $end_value = $what_item[$extract_field];
             $res_index[$index_key][] = $end_value;
             $res_index[$index_key]->linkers[] = $what_item;
         }
         //$res_index[$index_key][]= $extract_field ? $what_item[$extract_field] : $what_item;
     }
     foreach ($this as $our_item) {
         $check_value = $our_item[$check_field];
         $res_collection = isset($res_index[$check_value]) ? $res_index[$check_value] : fx::collection();
         $our_item[$res_field] = $res_collection;
         if ($our_item instanceof \Floxim\Main\Content\Entity && isset($res_collection->linkers)) {
             $res_collection->linkers->selectField = $our_item->getFormField($res_field);
         }
     }
     return $this;
 }