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

Model Realtion phalcon 3

Hello, I have a problem with model relation but i cant get a problem, please help to understand!

namespace Common\Models; use Phalcon\Mvc\Model; class Tags extends Model{

private $id;
private $name;
private $alias_uk;
private $alias_ru;

/**
 * @param mixed $name
 */
public function setName($name)
{
    $this->name = $name;
}

/**
 * @param mixed $alias_uk
 */
public function setAliasUk($alias_uk)
{
    $this->alias_uk = $alias_uk;
}

/**
 * @param mixed $alias_ru
 */
public function setAliasRu($alias_ru)
{
    $this->alias_ru = $alias_ru;
}

public function beforeValidation()
{
    $this->id=0;

}

public function initialize()
{
    $this->setSource($this->getDI()->get('config')->database->prefix . 'tags');
    $this->hasMany('id','\\Common\\Models\\TagsRelations','tag_id');
}

second model

namespace Common\Models; use Phalcon\Mvc\Model; class TagRelations extends Model{

private $id;
private $content_binder_id;
private $tag_id;

/**
 * @param mixed $content_binder_id
 */
public function setContentBinderId($content_binder_id)
{
    $this->content_binder_id = $content_binder_id;
}

/**
 * @param mixed $tag_id
 */
public function setTagId($tag_id)
{
    $this->tag_id = $tag_id;
}
public function beforeValidation()
{
    $this->id=0;

}

public function initialize()
{

    $this->setSource($this->getDI()->get('config')->database->prefix . 'tag_relations');
    $this->BelongsTo('tag_id','\\Common\\Models\\Tags','id');
}

}

and in controller

$tag=Tags::findFirst(['id'=>1]); print_r($tag->tagRelations);

and it gives me Access to undefined property Common\Models\Tags::tagRelations but with pure sql works and phsql

hi @denbit to get related records you have to use $model->getRelated('relation-name-or-alias', $optionalParams) but to set you can do this $model->tagRelations = [];

I advise you to always use aliases for your relationships to avoid problems

class Tags extends Model{
    public function initialize() {
        $this->hasMany('id',TagsRelations::class,'tag_id', ['alias' => 'relations']);
    }
}

class TagRelations extends Model{
    public function initialize() {
        $this->belongsTo('tag_id',Tags::class,'id', ['alias' => 'tag']);
    }
}

Good luck



347

thank you Emilio, but why is it nowhere documented? i've looked for everywhere and haven't found obligatory presence of alias for relations

hi @denbit is documented in model relationships. You are not obliged to use it but it is much easier to avoid problems