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

Models relationship with query

How is that, when I try to choose my columns in my query, I can't get the relationship virable? But if i dont choose any columns, it works - But then I can't set the LeftJoin data..

$categories = Self::query()
    ->columns(array('data as a.data'))
    ->leftJoin('Models\BlogsPostCategories', 'a.blogcatid = Models\BlogsBlogCategories.id', 'a')
    ->where('blogid = :blogid:', array('blogid' => $session['blogid']))
    ->orderBy('Models\BlogsBlogCategories.id DESC')
    ->execute();

     public function initialize()
{
    $this->hasOne('catid', __NAMESPACE__ . '\BlogsCategories', 'id', array(
        'alias' => 'info', 
    ));
    }

Hope you understand

You wrote it in wrong way. It should be a.data as data

edited May '16

i still cant get the info data, and i know that i need the a. alias, i just missed that when i typed it in.

You need to look at the $this->hasOne('catid', NAMESPACE . '\BlogsCategories', 'id', array( 'alias' => 'info', ));

Why can't i get info when i use the column...

You can, you just don't need as a.data. As means to rename column in mysql, so for example if you have same columns in two tables - then you need to use as.

I dont thing you understand my question.

Forget all about the data alias

Look at the $this->hasOne('catid', NAMESPACE . '\BlogsCategories', 'id', array( 'alias' => 'info', ));

Why is that I can't access the info alias, when I choose columns ??

leftJoin data is not the problem

But thanks for trying to help me :-)

Beacause it's alias for using only in model object. Not in queries. If you want alias to model you can set it in leftJoin. You need to join BlogsCategories if you want to access your relation.

But why does it work without column? If it dont set any columns it works?



145.0k
Accepted
answer
edited May '16

What you mean if you don't set any columns ? It works beacause you got full object and you can access info(and this will cause ADDITIONAL QUERY). When you selecting with columns you got partial objects (Phalcon\Mvc\Model\Row). Just use joins and columns, it's easy and best way to do.