lithium\data\model\Relationship::_embedHasMany()

protected method

Fetch hasMany related data to a whole collection and embed the result in it.

Parameters

  • mixed $collection

    A collection of data.

  • array $options

    The embed query options.

Returns

mixed

The fetched data.

Source

	protected function _embedHasMany(&$collection, $options) {
		$keys = $this->key();
		$formKey = key($keys);
		$toKey = current($keys);

		$related = [];

		$indexes = $this->_index($collection, $formKey);
		$related = $this->_find(array_keys($indexes), $options);
		$fieldName = $this->fieldName();

		foreach ($collection as $index => $entity) {
			if (is_object($entity)) {
				$entity->{$fieldName} = [];
			} else {
				$collection[$index][$fieldName] = [];
			}
		}

		foreach ($related as $index => $entity) {
			$isObject = is_object($entity);
			$values = $isObject ? $entity->{$toKey} : $entity[$toKey];
			$values = is_array($values) || $values instanceof Traversable ? $values : [$values];
			foreach ($values as $value) {
				$value = (string) $value;
				if (isset($indexes[$value])) {
					if ($isObject) {
						$source = $collection[$indexes[$value]];
						$source->{$fieldName}[] = $entity;
					} else {
						$collection[$indexes[$value]][$fieldName][] = $entity;
					}
				}
			}
		}

		return $related;
	}