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

Relationship model returning null

Hello

Model Reports

<?php

namespace Sample\Models;

use Phalcon\Mvc\Model;

class Reports extends Model {

  public $id;

  public $user_id;

public function initialize(){

    $this->belongsTo('user_id', 'Sample\Models\Users');

    $this->belongsTo('government_agency_id', 'Sample\Models\GovernmentAgencies', 'id');

}

}

Model Users

<?php namespace Sample\Models;

use Phalcon\Mvc\Model;

public $id;

public $user_id;

class Users extends Model {

public $id;

public function initialize(){
    $this->hasMany('id', 'Sample\Models\Reports', 'user_id');
}

}

Hello guys , Phalcon BelongsTo relationship is not working

when I fetch a Reports and try to get his Users - object returning null

$reports = Reports::findFirst(); echo $reports->Users->id;

$this->response->setJsonContent($reports->Users->id); return $this->response;

DISPLAY

NULL

edited Oct '15

Your belongsTo in your Reports model needs a 3rd paramater Instead of


$this->belongsTo('user_id', 'Sample\Models\Users');

it should be


$this->belongsTo('user_id', 'Sample\Models\Users', 'id');
edited Oct '15

Oh sorry , i forgot to include the third paramater in my question,

i already have this code and is not working

$this->belongsTo('user_id', 'Sample\Models\Users', 'id');

even the alias is not working

    $this->belongsTo(
        'users_id',
        'Sample\Models\Users',
        'id',
        array(
            'alias'    => 'users',
            'reusable' => true
        )
    );

@andreas thanks for the reply

Try with lowercase alias, "users", not "Users":

$reports = Reports::findFirst(); 
echo $reports->users->id;
$this->response->setJsonContent($reports->users->id); 
return $this->response;