P
P
Pavel2018-05-14 11:57:59
Yii
Pavel, 2018-05-14 11:57:59

How to access the columns of a joined table?

Hello!
There are a couple of tables in the content and category database. Models have been created for them and connections have been configured.
Both tables have the same fields: id, alias and a few more
In the content model

public function getCategory()
{
   return $this->hasOne(Category::class, ['id' => 'category_id']);
}

Now I want to get a joined table
$content = Content::find()
       ->select([
           Content::tableName() . '.alias',
           Content::tableName() . '.title',
           (другие нужные поля из таблиц content)
           'cat.alias catalias',
           (другие нужные поля из таблиц category)
       ])
       ->where([$tblContent.'.id' => $id])
       ->joinWith('category cat')
       ->one();

The data from the content table is available by its name in the $content object, but how do you get the data from the category table?
print_r($content->category); yields nothing
We managed to get the data only by creating properties in the Content class (public $catalias) and then accessing them as $content->catalias
Is there any other way to solve this problem?
And how to set the alias of the content table in such a query, so as not to write Content::tableName() . '.alias', right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2018-05-15
@html_profi

print_r($content->category); gives nothing

in your situation it is more correct option. And the code does not display anything, most likely because you assigned aliases to the fields from the category table in the query

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question