/** * Returns an array of linked objects containing the result set * * @api * @param string $sql <p> * "SELECT '__users', u.*, '__users_profile', up.* * FROM users u * LEFT JOIN users_profile up ON up.userId = u.id" * WHERE u.name = :name * </p> * @param array $params <p> * array (':name' => 'John') * </p> * @return array */ public function fetchRelations($sql, $params = array()) { $stmt = $this->prepare($sql, $params); $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); // prepare results $result = Relations::fetch($result); $stmt->closeCursor(); $this->ok(); return $result; }
/** * Get relation by name * @param string $modelName * @throws RelationNotFoundException * @return array */ public function getRelations($modelName) { if (!isset($this->relations[$modelName])) { $relation = Relations::findRelation($this, $modelName); if (empty($relation)) { throw new RelationNotFoundException('Can\'t found relation data for model "' . $modelName . '"'); } else { $this->relations[$modelName] = $relation; } } return $this->relations[$modelName]; }
/** * Get relations by model name * * @param string $modelName * @return array * @throws RelationNotFoundException */ public function getRelations($modelName) { if (!isset($this->relations[$modelName])) { $this->relations[$modelName] = Relations::findRelation($this, $modelName); } return $this->relations[$modelName]; }
/** * Setup relation "many to many" * [table1-key] [table1_key-table2-table3_key] [table3-key] * * @param string $model * @param string $link * @return void */ public function linkToMany($model, $link) { Relations::setRelations($this->model, $model, [$link]); }
/** * findRelation * * @param Row $row * @param string $relation * @return array * @throws Exception\RelationNotFoundException */ public static function findRelation($row, $relation) { $model = $row->getTable()->getModel(); /** @var \Bluz\Db\Table $relationTable */ $relationTable = Relations::getModelClass($relation); $relationTable::getInstance(); if (!($relations = Relations::getRelations($model, $relation))) { throw new RelationNotFoundException("Relations between model `{$model}` and `{$relation}` is not defined"); } // check many-to-many relations if (sizeof($relations) == 1) { $relations = Relations::getRelations($model, current($relations)); } $field = $relations[$model]; $key = $row->{$field}; return Relations::findRelations($model, $relation, [$key]); }