【问题标题】:How to connect Car_type, Model and Mark Car Laravel mysql如何连接 Car_type、Model 和 Mark Car Laravel mysql
【发布时间】:2026-01-18 18:50:01
【问题描述】:

我有一个汽车类型、品牌和型号表。当用户选择车型时,他会选择奥迪、宝马、奔驰。选择奥迪时,只获取奥迪等A1、A2、A3等车型。如果bmw win拿到X6、X4车型。我有三张桌子 1. 用汽车打字。 (目前只有 Car 后者可能是自行车) 2. 标记 3. 型号

如何用 Laravel eloquent 连接这三个表?

【问题讨论】:

    标签: mysql laravel eloquent relational-database


    【解决方案1】:
    --- car_types ---
    id        name
    1         sedan
    2         hatchback
    3         sport
    4         suv
    
    -- car_brands ---
    id        name
    1         bmw
    2         mercedes
    3         audi
    
    -- car_models --
    id        brand_id    model_name  car_type
    1         3           A1          1
    2         3           A2          1
    3         3           A3          1
    4         3           Q7          4
    5         1           X5          4
    6         1           X6          4
    7         1           X7          4
    8         2           AMG         3
    9         3           A1          2
    
    
    -- cars --
    id model_id brand_id model_year name             ...other fields
    1  1        3        2018       Audi A1 1.0 2018
    2  3        3        2017       Audi A3 1.6 2017
    
    on cars table brand_id* is optional foreign key as shortcut for reaching car's brand.
    

    关系:

    1. 一种车型有很多车型。 (国外:car_models.car_type > car_types.id)
    2. 一个汽车品牌有很多车型。 (国外:car_models.brand_id > car_brands.id)
    3. 汽车属于汽车模型。 (国外:cars.model_id > car_models.id)
    4. 汽车属于汽车品牌。 (国外:cars.brand_id > car_brands.id)

    【讨论】:

      【解决方案2】:

      假设你有模型

      CarType 用于汽车类型表 CarBrand 用于 car_brands 表和 CarModel 用于 car_models 表

      您可以使用 Eloquent:Relationships 来实现此目的

      在您的 CarType 模型中

      <?php
      
      namespace App;
      
      use Illuminate\Database\Eloquent\Model;
      
      class CarType extends Model
        {
          /**
           * Get the brands for the car .
           */
          public function brands()
        {
          return $this->hasMany('App\CarBrand');
        }
      }
      

      在您的 CarBrand Model 中,您可以使用获取品牌所属的汽车类型

      <?php
      
       namespace App;
      
       use Illuminate\Database\Eloquent\Model;
      
       class CarBrand extends Model
       {
         /**
         * Get the car that owns the brand.
         */
        public function carType()
        {
          return $this->belongsTo('App\CarType');
        }
      }
      

      例如,你可以这样做

      $car = Car->find(1); // to get car with ID 1.
      $brands = $car->brands; // brands of the selected car. You can loop through now
      

      另外,对于品牌,你可以这样做

      $brand = Brand->find(1) // For Brand ID 1
      $car = $brand->carType;
      

      您可以查看Eloquent Relationships

      【讨论】:

      • 好吧,但我还没有 car_type?
      • 如果你只是通过我上面给出的例子并阅读关系文档,你就会明白