Loading...

How to connect via an eloquent relation in the Laravel table Type_Vehicle, Mark, Model table


I need to make 3 dropdowns. When selecting Vehicle_Type, only the Car will get it. When Vehicle_type = Car is selected, Mark is chosen for example Audi, Bmw, Mercedes. When Mark is selected, the model is chosen, but the model must be, for example, if I selected Audi to get A3, A4, A5. If the user chooses BMW gets it as a model X5, X6 and so on. Look at my tables below. QUESTION I need to connect models and get the queries? There is also a car table that should not be mentioned with these tables, at least I think.

Vehicle_type or car_type table:

    Schema::create('car_types', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

Mark table:

    Schema::create('marks', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('car_type_id');
        $table->timestamps();
    });

car_models table:

    Schema::create('car_models', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('car_type_id');
        $table->integer('mark_id');
        $table->timestamps();
    });

Car_type model:

class Car_type extends Model
{
   ??????
}

Mark model:

class Mark extends Model
{
  ??????
}

CarModel model:

class CarModel extends Model
{
    ??????
}
- - Source

Answers

answered 1 week ago Brad #1

You probably don't need car_type_id on your car_models table:

Schema::create('car_models', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->integer('mark_id');
    $table->timestamps();
});

Should be sufficient.

Car_type model:

class Car_type extends Model
{
    public function marks() {
        return $this->hasMany(Mark::class);
    }
}

Mark model:

class Mark extends Model
{
    public function car_type() {
        return $this->belongsTo(Car_type::class);
    }
    public function models() {
        return $this->hasMany(CarModel::class);
    }
}

CarModel model:

class CarModel extends Model
{
    public function mark()
    {
        return $this->belongsTo(Mark::class);
    }
}

comments powered by Disqus