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

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'"


3.9k

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()


77.7k
Accepted
answer
edited Oct '16

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

https://docs.phalcon.io/en/latest/api/Phalcon_Mvc_Model_Resultset_Simple.html (url formatting sucks on the forums =/ )



3.9k

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