Search code examples
phpactiverecordphalconvolt

Phalcon - Lazy loading is not working in Models for some strange reason


I am new to phalcon and coming from more of Symfony background, i just need to know how define optional relationship between foreign keys in phalcon models.

i.e Users table PK is user_id, and Users May have(Optional) related record in Photos table to have photo with primary key photo_id and linked by 'user_id'.

So in my falcon models i need to load Users with the photos if there is a one.

In user model

 public function initialize()
{
    $this->hasMany(
        "photo_id",
        "Photo",
        "photo_id",
        array(
            'alias' => 'photos'
        )
    );
}

IN photo model i write it as

public function initialize()
{
    $this->belongTo(
        "user_id",
        "User",
        "user_id",
        array(
            'alias' => 'user'
        )
    );
}

In volt to access to it via

{{user.photo.photo_id}}

But this gives me error

Undefined property: Phalcon\Mvc\Model\Resultset\Simple::$photo_id

Any idea ?

Strangely if do this code in the controller it works and get me the photo models but not when i try to access it with lazy loading /

$users = User::find(array(
"limit" => 10)
);
echo "There are ", count($users), "\n";
foreach($users as $user){
$photos = Photo::find(array(
"user_id=:user_id:",
"limit" => 10,
"bind" => array("user_id" => $user->user_id)
)
);
if($photos->count()==0){
echo "<br />";
echo "No photo found for user".$user->user_id;
}
foreach($photos as $photo){
echo '<br />';
echo "User ->".$photo->user_id." Photo -> ".$photo->photo_id;
}
}

When i try to do it with lazy loading like this

foreach($users as $user){
    //echo $user->photos->photo_id;
    foreach($user->photos as $photo){
        echo '<br />';
        echo "User ->".$photo->user_id."  Photo -> ".$photo->photo_id;
    }
 }

I get the error:

Undefined property: Phalcon\Mvc\Model\Resultset\Simple::$photo_id


Solution

  • Issue seems to be caused by i am having two database connections like below which is causing some problems in the DI set.

    return new \Phalcon\Config(array(
        'database'    => array(
            'adapter'  => 'Mysql',
            'host'     => 'localhost',
            'username' => 'root',
            'password' => '',
            'dbname'   => 'db_main',
            'name'   => 'db_main',
        ),
    

    needs to keep only one database with name "dbname";

    thats all i did to fix