A
A
andrew-corput2018-07-23 09:08:19
Laravel
andrew-corput, 2018-07-23 09:08:19

How to implement the choice of model by manufacturer?

I imagine it like this:
Tables

Goods - goods table, contains id, brand_id, model_id fields.

Brands - table with brand names, contains id, name fields

Models - table with model names, contains id, parent_id, name fields

You will need to display the product in the form "Manufacturer: {{ brand_id (name) }} model {{ model_id (name) }}".
I have no idea how to link the tables in such a way that when choosing a manufacturer, you can select only the models that correspond to it.
The third day I can not deal with this issue, I did not find similar examples. experience is not great, preferably an example.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Popov, 2018-07-23
@andrew-corput

1) It is not clear why you made a many-to-many relationship. After all, one product can have only one producer, and one producer can have many products. An O:M relationship emerges . It is done classically - in the product table, the brand_id column. In the brand model, the method

public function models()
{
    return $this->hasMany(Model::class);
}

A similar method is in the model of the model (tautology)
public function brands()
{
    return $this->belongsTo(Brand::class);
}

Extract like this:
Model::findOrFail($id)->brand->name;
//Или так
Brand::findOrFail($id)->models()->where('id', $id)->first()->name;
//Или так во вьюшке
@foreach(Brand::findOrFail($id)->models as $model)
Производитель {{$brand->name}} : модель {{$model->name}}
@endforeach

2) If it is directly critical for you to make a many-to-many choice , then the selection is made using whereHas

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question