/** * @param DataMapper $data * @return null|Entity|Entity[] */ public function getResult(DataMapper $data) { $results = $this->loadResults(); $pk = $data->getColumn($this->primaryKey); if ($this->hasMany) { $all = []; foreach ($this->keys as $key => $id) { if ($id === $pk) { $all[] = $results[$key]; } } return $all; } foreach ($this->keys as $key => $id) { if ($id === $pk) { return $results[$key]; } } return null; }
/** * @param DataMapper $data * @param callable|null $callback * @return mixed */ protected function getResult(DataMapper $data, callable $callback = null) { $manager = $data->getEntityManager(); $related = $manager->resolveEntityMapper($this->entityClass); if ($this->foreignKey === null) { $this->foreignKey = $related->getForeignKey(); } $statement = new SQLStatement(); $select = new EntityQuery($manager, $related, $statement); $select->where($related->getPrimaryKey())->is($data->getColumn($this->foreignKey)); if ($this->queryCallback !== null || $callback !== null) { $query = new Query($statement); if ($this->queryCallback !== null) { ($this->queryCallback)($query); } if ($callback !== null) { $callback($query); } } return $select->get(); }
/** * @param DataMapper $data * @param $items */ public function unlink(DataMapper $data, $items) { if (!is_array($items)) { $items = [$items]; } $manager = $data->getEntityManager(); $owner = $data->getEntityMapper(); $related = $manager->resolveEntityMapper($this->entityClass); if ($this->junctionTable === null) { $table = [$owner->getTable(), $related->getTable()]; sort($table); $this->junctionTable = implode('_', $table); } if ($this->juctionKey === null) { $this->juctionKey = $related->getForeignKey(); } if ($this->foreignKey === null) { $this->foreignKey = $owner->getForeignKey(); } $table = $this->junctionTable; $col1 = $this->foreignKey; $col2 = $this->juctionKey; $val1 = $data->getColumn($owner->getPrimaryKey()); $val2 = []; $key = $related->getPrimaryKey(); $connection = $manager->getConnection(); $extractor = function () use($key) { return $this->orm()->getColumn($key); }; foreach ($items as $item) { $val2[] = is_subclass_of($item, $this->entityClass, false) ? $extractor->call($item) : $item; } try { (new Delete($connection, $table))->where($col1)->is($val1)->andWhere($col2)->in($val2)->delete(); } catch (\Exception $e) { //ignore } }