我有两个表,其中一个是 car_category ,其字段为 id,类型。 另一个名为车辆的表格包含字段 - c_id (FK指汽车 - id)。 现在我想显示FK(c_id)值 car -type。 我在模型中使用了以下代码,
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";
我怎样才能做到这一点?有人能帮助我吗?
答案 0 :(得分:1)
要获取Car
及其Vehicle
信息,您可以使用Eager Loading进行查询
$result = Car::with('vehicles')->get();
在未指定FQN的情况下,您已将类名指定为字符串文字,还应使用完全限定名称定义模型中的关系
汽车模型
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany(\App\Models\Vehicle::class);
}
}
车辆型号
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(\App\Models\Car::class);
}
}
答案 1 :(得分:1)
试试这个
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外键。如果要覆盖此约定,可以将第二个参数传递给方法
要获取汽车及其车辆信息,您可以使用预先加载
进行查询$result = Car::with('vehicles')->get();
答案 2 :(得分:0)
从class car
更改为class Car
之后,您可以选择Car::first()
,相关的表格数据可以在Car::first()->vehicles
您还可以在模型上添加where()方法,如果您有多个记录,请使用foreach()
答案 3 :(得分:0)
In Model,
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(Car::class, 'c_id');
}
}
在控制器中,
$vehicles = Vehicle::all();
return view('vehicles.vehicle',['vehicles'=>$vehicles]);