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

How to get data via related

Hello all

I have a problem see below:

In model Users have id and some field

 /**
     * Get all of the subscriptions for the user.
     *
     */
    public function subscriptions()
    {
        return $this->hasMany('id', Subscription::class, 'user_id', ['alias' => 'subscriptions']);
    }

Model Subscription have field user_id and some fields, and I call this function

        $user = Users::findFirst();
        var_dump($user->subscriptions());

After that I running the code above which the result below

Phalcon\Mvc\Model\Relation Object
(
    [_type:protected] => 2
    [_referencedModel:protected] => App\Cashier\Subscription
    [_fields:protected] => id
    [_referencedFields:protected] => user_id
    [_intermediateModel:protected] => 
    [_intermediateFields:protected] => 
    [_intermediateReferencedFields:protected] => 
    [_options:protected] => Array
        (
            [alias] => subscriptions
        )

)

So I need to get data relation table users with subscription, how to do that without use initialize method:

Note: If I defined a function initialize in model users

public function initialize()
    {

        $this->hasMany('id', Subscription::class, 'user_id', ['alias' => 'subscriptions']);
    }

I can get it easy with $user->subscriptions



145.0k
Accepted
answer
    public function subscriptions()
    {
        return $this->getRelated('subscriptions');
    }

Or just $user->subscriptions.

This:

$this->hasMany('id', Subscription::class, 'user_id', ['alias' => 'subscriptions']);

Is just definition of relation. It returns relation object.



58.4k
edited May '16

Hello Wojciech

Thanks your sugesstion and It work, here my code

public function subscriptions()
{
    $this->hasMany('id', Subscription::class, 'user_id', ['alias' => 'subscriptions']);
    return $this->getRelated('subscriptions');
}
$this->hasMany('id', Subscription::class, 'user_id', ['alias' => 'subscriptions']);

This is not necessary, just put this only into initialize method.