gpt4 book ai didi

php - 如何在 Laravel 中选择外键值

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:44 25 4
gpt4 key购买 nike

我有两个表,一个是 car_category,它有字段 - id,type。另一个名为 vehicle 的表具有字段 - c_id(FK 指 car - id)。现在我想显示 car 类型的 FK(c_id) 值。我在模型中有以下代码,

class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';

public function vehicles()
{
return $this->hasMany('Vehicle');
}
}

车辆模型,

class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo('Car');
}
}

我对此的查询是什么?我试过这段代码,结果出错。

$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles 
WHERE cars.id = vehicles.c_id";

我怎样才能做到这一点?谁能帮帮我?

最佳答案

试试这个

class Car extends Model  
{
protected $guarded = [];
protected $table = 'car_category';

public function vehicles()
{
return $this->hasMany(Vehicle::class, 'c_id');
}
}

车辆型号

 class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';

public function cars()
{
return $this->belongsTo(Car::class, 'c_id');
}
}

Eloquent 根据模型名称确定关系的外键。在这种情况下,Car 模型被自动假定为具有 car_id 外键。如果您希望覆盖此约定,您可以将第二个参数传递给该方法

https://laravel.com/docs/5.5/eloquent-relationships#one-to-one

要获取汽车及其车辆信息,您可以使用预加载进行查询

$result = Car::with('vehicles')->get();

关于php - 如何在 Laravel 中选择外键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47647492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com