M
M
Maxim Osadchy2017-08-19 14:26:37
Yii
Maxim Osadchy, 2017-08-19 14:26:37

How to merge a sequence of tables in yii2?

Hello!
I started to study yii2, according to the lesson I created a category tree in a component in which an associative array is formed.
The problem is that the urls for the categories are in a separate table.
The call itself in the component:

$this->data = Category::find()->indexBy('id')->asArray()->all();

Category class:
class Category extends ActiveRecord
{
    public static function tableName()
    {
        return 'categories';
    }

    public function getProducts()
    {
        return $this->hasMany(Product::className(), ['category_id' => 'id']);
    }
}

Product class:
class Product extends ActiveRecord
{
    public static function tableName()
    {
        return 'products';
    }

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

I wrote the third class CategoriesUrl, in which, in theory, selection and join in the category should take place, but I don’t really understand how to do this:
class CategoriesUrl extends ActiveRecord
{
    public static function tableName()
    {
        return 'categories_url';
    }
}

The categories_url.category_id field should look at categories.id.
I would be grateful for answers/links to manuals.
UPD : join turned out, but not as much as we would like. I needed to add everything to one array, but a multidimensional one was created:
3] => Array
        (
            [id] => А3
            [name] => DVD и CD диски
            [description] => 
            [meta_keywords] => 
            [meta_description] => 
            [parent_id] => 
            [enabled] => 1
            [updated] => 2017-07-31 00:07:59
            [categoriesUrl] => Array
                (
                    [category_id] => А3
                    [url] => a3
                    [url_title] => dvd-i-cd-diski
                    [new] => 0
                    [description] => 
                    [meta_keywords] => 
                    [meta_description] => 
                    [product_name_template] => %name% - %sku%
                )

        )

Here is the challenge:
$this->data = Category::find()->indexBy('id')->joinWith('categoriesUrl')->asArray()->all();

And here is the getCategoriesUrl method itself:
public function getCategoriesUrl()
    {
        return $this->hasOne(CategoriesUrl::className(), ['category_id' => 'id']);
    }

Can you tell me where is the mistake?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Access Denied, 2017-08-19
@AccessDenied80

https://yiiframework.com.ua/ru/doc/guide/2/db-acti...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question