如何在 Laravel 中选择外键值

use*_*est 2 php mysql laravel-5

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

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

    public function vehicles()
    {
        return $this->hasMany('Vehicle');
    }
}
Run Code Online (Sandbox Code Playgroud)

车辆型号,

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

我对此有何疑问?我试过这段代码,结果错误。

$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles 
             WHERE cars.id = vehicles.c_id";
Run Code Online (Sandbox Code Playgroud)

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

Biv*_*vin 6

尝试这个

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

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

车辆型号

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

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

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

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

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

$result = Car::with('vehicles')->get();
Run Code Online (Sandbox Code Playgroud)