Php 如何在Laravel中选择外键值

Php 如何在Laravel中选择外键值,php,mysql,laravel-5,Php,Mysql,Laravel 5,我有两个表,一个是汽车类别有字段-id,键入。 另一个名为vehicle的表具有字段-c_id(FK指car-id)。 现在我想显示FK(c_id)值,它是car类型。 我在模型中有以下代码 class Car extends Model { protected $guarded = []; protected $table = 'car_category'; public function vehicles() { return $this-&

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

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";

我怎样才能做到这一点?有人能帮我吗?

班车
换成
班车

之后,您可以使用
Car::first()
进行选择,相关表格数据可以在
Car::first()->vehicles


您还可以在模型上添加where()方法,如果您有多条记录,请使用foreach()

获取
Car
及其
Vehicle
信息,您可以使用

您将类名指定为字符串文字而未指定的另一个更正是,应该使用完全限定名定义模型中的关系

汽车模型

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);
    }
}
试试这个

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根据模型名称确定关系的外键。在这种情况下,将自动假定汽车模型具有汽车id外键。如果希望重写此约定,可以将第二个参数传递给该方法


要获取车辆及其车辆信息,您可以使用“快速加载”进行查询

在控制器中

    $vehicles = Vehicle::all();
    return view('vehicles.vehicle',['vehicles'=>$vehicles]);

你的类车应该是
car
查询有什么错误吗?我对你的表感到困惑,在查询中,您有
汽车
汽车
,而模型有
汽车
汽车
汽车
是关系模型的函数名。
在hasrelations.php(第487行)中找不到'Vehicle'类@saranya我已经给出了我的答案,如果您对您的车型使用了不同的名称空间,而不是
App\models
,那么我建议您在定义relationshipsOk时使用正确的名称空间。如何在视图blade中获取表数据。通过
$result->vehicles->car u type对吗?@saranya是的,将其传递给查看,然后循环查看您的数据,然后循环查看每辆车的
车辆
。当我添加结果时,它只提供汽车表数据谢谢,但查询应该是什么?要获取汽车及其车辆信息,可以使用渴望加载$result=car::with('vehicles')->get()进行查询;确定并使用
$result->vehicles->car\u type获取车辆表的数据不是吗?你能给我举个例子吗?
$result = Car::with('vehicles')->get();
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]);