Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

serializing a model with an association #577

Open
Hodor9898 opened this issue Jul 24, 2017 · 0 comments
Open

serializing a model with an association #577

Hodor9898 opened this issue Jul 24, 2017 · 0 comments

Comments

@Hodor9898
Copy link

trying to serialize a model with using the include option will not trigger the associated model`s to_array() function

for example

class User extends ActiveRecord\Model {
    static $belongs_to = array('owner');
    
    function to_array(array $options = array()) {
        $arr = parent::to_array($options);
        $arr['custom_user_attribute'] = 'This value will be added';
        
        return $arr;
    }
}

class Owner extends ActiveRecord\Model {
    function to_array(array $options = array()) {
        $arr = parent::to_array($options);
        $arr['custom_owner_attribute'] = 'This value will not be displayed';
        
        return $arr;
    }
}


$user = User::find(1);
$user->to_array(array(
    'include' => array(
        'owner'
    )
));

i solved this by either manually using the associated models **to_array()** function or updating the **Serialization.php** files check_include() function:

	private function check_include()
	{
		if (isset($this->options['include']))
		{
			$this->options_to_a('include');

			$serializer_class = get_class($this);

			foreach ($this->options['include'] as $association => $options)
			{
				if (!is_array($options))
				{
					$association = $options;
					$options = array();
				}

				try {
					$assoc = $this->model->$association;

					if ($assoc === null)
					{
						$this->attributes[$association] = null;
					}
					elseif (!is_array($assoc))
					{
						$this->attributes[$association] = $assoc->to_array($options);
					}
					else
					{
						$includes = array();

						foreach ($assoc as $a)
						{

							if ($this->includes_with_class_name_element)
								$includes[strtolower(get_class($a))][] = $a->to_array($options);
							else
								$includes[] = $a->to_array($options);
						}

						$this->attributes[$association] = $includes;
					}

				} catch (UndefinedPropertyException $e) {
					;//move along
				}
			}
		}
	}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant