C
C
chelkaz2016-10-29 00:52:56
Laravel
chelkaz, 2016-10-29 00:52:56

How to simplify the handling of getting shared data?

In one category table.
In the second elements.
In the third color for the elements.
All of them are connected.
The point is to show in the category all the colors that its elements use.
Now I'm getting like this.

$categories = Category::with('elements.colors')->get();

And I'm sorting through them in my head:
@foreach($category->elements as $element)
        {{$element->colors->code}}
@endforeach

But here are the problems, I only need different colors, and not everything. And secondly, if a category has 1000 elements, and there are 100 categories on the page, what then? How can I simplify, or is my logic initially wrong?
Category to hasMany
elements Category belongsTo elements
And colors to belongsTo elements

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2016-10-29
@qonand

You approach the task a little wrong - you need to display the unique color values ​​used in the category elements, which means you need to create a relation in the category model that will get this data through the colors linking table. In Yii, it might look something like this:

class Category extends \yii\db\ActiveRecord{
// .....

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

    public function getColors(){
        return $this->hasMany(Color::className(), ['id' => 'element_id'])
                   ->via('elements')->distinct();
    }
// ...

H
hakkol, 2016-10-31
@hakkol

https://laravel.com/docs/5.3/collections#method-unique

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question