我有一款车,牌子和型号表。当用户选择汽车类型时,他会得到奥迪、宝马、梅赛德斯。在选择奥迪时,它只获得奥迪etc A1,A2,A3的车型。如果宝马赢得X6,X4车型。我有三张桌子1.打字和汽车。(目前唯一的汽车可能是自行车) 2.马克3.模型
如何将这三个表与Laravel eloquent连接起来?
发布于 2019-03-14 20:52:23
--- 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.关系:
> cars.brand_id
发布于 2019-03-14 21:16:55
假设你有一个模型
CarType for Cars Types表CarBrand for 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模型中,您可以使用以下命令获取品牌所属的汽车类型
<?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;https://stackoverflow.com/questions/55162607
复制相似问题