首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何连接Car_type、Model和Mark Car Laravel mysql

如何连接Car_type、Model和Mark Car Laravel mysql
EN

Stack Overflow用户
提问于 2019-03-14 20:30:59
回答 2查看 400关注 0票数 0

我有一款车,牌子和型号表。当用户选择汽车类型时,他会得到奥迪、宝马、梅赛德斯。在选择奥迪时,它只获得奥迪etc A1,A2,A3的车型。如果宝马赢得X6,X4车型。我有三张桌子1.打字和汽车。(目前唯一的汽车可能是自行车) 2.马克3.模型

如何将这三个表与Laravel eloquent连接起来?

EN

回答 2

Stack Overflow用户

发布于 2019-03-14 20:52:23

代码语言:javascript
复制
--- 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. A汽车类型hasMany汽车型号。(国外:品牌> car_types.id)
  2. A Car car_models.car_type hasMany Car Models.( car_brands.id)
  3. A : car_models.brand_id > Car belongsToA Car Model.(国外: cars.model_id > car_models.id)
  4. A Car belongsTo A Car Brand.(外部: car_brands.id)

> cars.brand_id

票数 0
EN

Stack Overflow用户

发布于 2019-03-14 21:16:55

假设你有一个模型

CarType for Cars Types表CarBrand for car_brands表和CarModel car_models表

您可以使用Eloquent: Relationships来实现这一点

在CarType模型中

代码语言:javascript
复制
<?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模型中,您可以使用以下命令获取品牌所属的汽车类型

代码语言:javascript
复制
<?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');
  }
}

例如,您可以这样做

代码语言:javascript
复制
$car = Car->find(1); // to get car with ID 1.
$brands = $car->brands; // brands of the selected car. You can loop through now

此外,对于品牌,您可以这样做

代码语言:javascript
复制
$brand = Brand->find(1) // For Brand ID 1
$car = $brand->carType;

你可以查看Eloquent Relationships

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55162607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档