Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

One to Many relationship, Accesing properties

Hello, I'm trying to get the 'value' of a 'key' corresponding to a Metadata of a User but I can't find the way of doing it.

I have two models, User and UserMeta:

namespace MyApp\Models;
class User extends \Phalcon\Mvc\Model
{
    public $id;
    public $email;
    public function initialize()
    {
        $this->hasMany('id', __NAMESPACE__ . '\UserMeta', 'user_id', ['alias' => 'userMeta']);
    }
}
namespace MyApp\Models;
class UserMeta extends \Phalcon\Mvc\Model
{
    public $id;
    public $user_id;
    public $key;
    public $value;
    public function initialize()
    {
        $this->belongsTo('user_id', __NAMESPACE__ . '\User', 'id', ['alias' => 'user']);
    }
}

I have these tables:

User table
+----+---------------+
| id | email         |
+----+---------------+
| 1  | [email protected]   |
+----+---------------+

UserMeta table
+----+------------+----------------+--------------+
| id | user_id    | key            | value        |
+----+------------+----------------+--------------+
| 1  | 1          | first_name     | Smith        |
+----+------------+----------------+--------------+

What I'm trying to do is to access the value for the 'first_name' key in the UserMeta Model.

I mean, I'm trying to get the First Name of user '[email protected]' -> "Smith"

I'm doing it in this way:

$email = "[email protected]";
$user = User::findFirstByEmail($email);
$firstName = $user->getUserMeta(["key" => "first_name"])->value;

But I can't get results

Does somebody know what is the best way of doing this?

edited Oct '16

Firs of all all hasMany return resultset(set of rows). So you need to access row. Second this syntax: ["key" => "first_name"] won't work. You need to use something like

"key = 'first_name'"


1.3k

Thanks for the correction! Then I have this

$user->getUserMeta(["key = 'first_name'"])

What should I do next, because using:

$user->getUserMeta(["key = 'first_name'"])->findFirst()->value

It's trowing me errors:

Fatal error: Uncaught Error: Call to undefined method Phalcon\Mvc\Model\Resultset\Simple::findFirst()


38.6k
Accepted
answer
edited Oct '16

It should be getFirst() instead of findFirst(), you're calling it on a ResultSet

https://docs.phalconphp.com/en/latest/api/Phalcon%5Mvc%5Model%5Resultset%5Simple.html (url formatting sucks on the forums =/ )



1.3k

Wow! great!

Thanks Wojciech for correcting my mistakes, i'm still in basic-mode :)

And thanks Lajos you helped me so much with the class method and that url

Now it's working

This is the way:

$user->getUserMeta(["key = 'first_name'"])->getFirst()->value