We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Get related user information

Hi,

I have a few tables liked together for storing user information, but I can't seem to get the related information by key.

The models are:

<?php

namespace Common\Coopunity\Models;
use Phalcon\Exception;

/**
 * Class Users
 * @package Common\Coopunity\Models
 * @author Andre Figueira <[email protected]>
 */
class Users extends \Phalcon\Mvc\Model
{
    /**
     * @var integer
     */
    protected $id;

    /**
     * @var string
     */
    protected $type;

    /**
     * @var string
     */
    protected $email;

    /**
     * @var string
     */
    protected $username;

    /**
     * @var string
     */
    protected $name;

    /**
     * @var string
     */
    protected $password;

    /**
     * @var string
     */
    protected $date;

    /**
     * Map the table columns to camelCase.
     *
     * @return array
     */
    public function columnMap()
    {
        return array(
            'id' => 'id',
            'type' => 'type',
            'username' => 'username',
            'name' => 'name',
            'email' => 'email',
            'password' => 'password',
            'date' => 'date',
        );
    }

    /**
     * Setup relationships.
     */
    public function initialize()
    {
        $this->hasMany(
            'id',
            'Common\Coopunity\Models\UsersSettings',
            'settingsId',
            array(
                'alias' => 'usersSettings'
            )
        );

    }

    /**
     * Checks if a user exists with a specific username.
     *
     * @param $username
     *
     * @return bool
     */
    public static function usernameInUse($username)
    {
        return (bool) Users::count('username = "'.$username.'"');
    }

    /**
     * Checks if a user exists with a specific email.
     *
     * @param $email
     *
     * @return bool
     */
    public static function emailInUse($email)
    {
        return (bool) Users::count('email = "'.$email.'"');
    }

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @param string $type
     *
     * @return $this
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param string $email
     *
     * @return $this
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * @param string $username
     *
     * @return $this
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     *
     * @return $this
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param string $password
     *
     * @return $this
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @return string
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * @param string $date
     *
     * @return $this
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    public static function fetchUsersSettings($usersId)
    {
        $user = new Users();

        $settings = $user->getModelsManager()->createBuilder()
            ->columns(array(
                'Common\Coopunity\Models\Settings.key as key',
                'Common\Coopunity\Models\UsersSettings.value as value',
            ))
            ->from('Common\Coopunity\Models\Settings')
            ->leftJoin('Common\Coopunity\Models\UsersSettings', 'Common\Coopunity\Models\UsersSettings.usersId = "' . $usersId . '"')
            ->where('Common\Coopunity\Models\Settings.id = Common\Coopunity\Models\UsersSettings.settingsId')
            ->getQuery()
            ->execute();

        $userSettings = new UserSettings();

        foreach ($settings as $setting) {
            $setterNameKey = ucfirst($setting->key);
            $setterName = 'set' . $setterNameKey;

            if (method_exists($userSettings, $setterName)) {
                $userSettings->{$setterName}($setting->value);
            } else {
                throw new Exception('Non existent settings setter: ' . $setterName);
            }
        }

        return $userSettings;
    }

    public function afterFetch()
    {
        $this->attributes = Users::fetchUsersSettings($this->id);
    }
}
<?php

namespace Common\Coopunity\Models;

/**
 * Class Settings
 * @package Common\Coopunity\Models
 * @author Andre Figueira <[email protected]>
 */
class Settings extends \Phalcon\Mvc\Model
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var string
     */
    protected $key;

    /**
     * Setup relationships.
     */
    public function initialize()
    {
        $this->hasMany(
            'id',
            'Common\Coopunity\Models\UsersSettings',
            'settingsId',
            array(
                'alias' => 'settings',
            )
        );
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * @param mixed $key
     *
     * @return $this
     */
    public function setKey($key)
    {
        $this->key = $key;

        return $this;
    }

    /**
     * Map the table columns to camelCase.
     *
     * @return array
     */
    public function columnMap()
    {
        return array(
            'id' => 'id',
            'key' => 'key',
        );
    }

}
<?php

namespace Common\Coopunity\Models;

/**
 * Class UsersSettings
 * @package Common\Coopunity\Models
 * @author Andre Figueira <[email protected]>
 */
class UsersSettings extends \Phalcon\Mvc\Model
{
    /**
     * @var int
     */
    protected $id;

    /**
     * @var int
     */
    protected $settingsId;

    /**
     * @var int
     */
    protected $usersId;

    /**
     * @var string
     */
    protected $value;

    /**
     * Id for the profilePictureOriginal key
     */
    const ID_PROFILE_PICTURE_ORIGINAL = 1;

    /**
     * Id for the profilePictureLarge key
     */
    const ID_PROFILE_PICTURE_LARGE = 2;

    /**
     * Id for the profilePictureSmall key
     */
    const ID_PROFILE_PICTURE_SMALL = 3;

    /**
     * Id for the bannerPicture key
     */
    const ID_BANNER_PICTURE = 4;

    /**
     * Setup relationships.
     */
    public function initialize()
    {
        $this->setSource('users_settings');

        $this->belongsTo(
            'settingsId',
            'Common\Coopunity\Models\Settings',
            'id'
        );

        $this->belongsTo(
            'usersId',
            'Common\Coopunity\Models\Users',
            'id'
        );
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     *
     * @return $this
     */
    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return int
     */
    public function getSettingsId()
    {
        return $this->settingsId;
    }

    /**
     * @param int $settingsId
     *
     * @return $this
     */
    public function setSettingsId($settingsId)
    {
        $this->settingsId = $settingsId;

        return $this;
    }

    /**
     * @return int
     */
    public function getUsersId()
    {
        return $this->usersId;
    }

    /**
     * @param int $usersId
     *
     * @return $this
     */
    public function setUsersId($usersId)
    {
        $this->usersId = $usersId;

        return $this;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * @param string $value
     *
     * @return $this
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * Map the table columns to camelCase.
     *
     * @return array
     */
    public function columnMap()
    {
        return array(
            'id' => 'id',
            'settings_id' => 'settingsId',
            'users_id' => 'usersId',
            'value' => 'value',
        );
    }

}

The database stucture is:

users:

  • id
  • name

settings:

  • id
  • key

usersSettings:

  • usersId
  • settingsId
  • value

I have a setting record called originalProfilePicture with id 1 I have a user record with id 1 I have a user setting record with usersId 1 and settingsId 1 with a profile picture url

I am attempting to from an instance of the user model fetch the value of the picture based on the key.

e.g.

$user = Users::findFirstById(1);
echo $user->usersSettings->originalProfilePicture;

I know the query to fetch what I need is being run, as I can see it in my profiler:

SELECT `settings`.`key` AS `key`, `users_settings`.`value` AS `value` FROM `settings` LEFT JOIN `users_settings` ON `users_settings`.`users_id` = '1' WHERE `settings`.`id` = `users_settings`.`settings_id`

But I can';t seem to get it out of the user object. Help would be great! Thanks in advance.

$user->usersSettings is a Resultset not a Model



58.4k
Accepted
answer

Hey

In models UsersSettings you tried add set/get propety "originalProfilePicture".

then call it $user->usersSettings->getoriginalProfilePicture()

It's ok, I've sorted out the issue.