W
W
WebDev2016-02-04 15:37:45
Laravel
WebDev, 2016-02-04 15:37:45

How to attach a model in laravel?

This model structure:
-Category
-Param
-ParamsToCategory
-ParamsValue
In the Category model I specify:

public function params()
    {
        return $this->hasManyThrough('Param', 'ParamsToCategory', 'category_id', 'id');
    }

In the Param model:
public function values()
    {
        return $this->hasMany('ParamsValue');
    }

Question: How can I get this result in one expression:
Category1: [
    id
    name
    params : [
        id
        name
        values : [
            id,
            name,
            ...
        ]
    ]
]

That is, if it’s just a category with parameters, then I write
Category::with('params')->find($id);
And now I need something like this:
Category::with('params')->with('values')->find($id)->toArray();

Но это не работает.
Как мне достать параметры категории и их значения с помощью моделей, без sql?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kamol, 2016-02-04
@kirill-93

Попробуйте типа так:
Если внешние ключи правильно установлены, то подтягивает все values и params данной категории

S
Stanislav Pochepko, 2016-02-04
@DJZT

Category::with('params')->find($id);The construction is needed only if you do not want to make a request while accessing the params model parameter. Then the result will immediately lie there. In general, the stuy does not change much.

$Cat = Category::with('params')->find($id);
foreach(Cat->params as $param){
 foreach($param->values as $value){
echo $value->{свойство};
}
}

I understand that you need to understand this? I advise you to slightly tighten up your knowledge about database relations

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question