Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select foreign key value in Laravel

I've two tables one is car_category having the fields - id,type. Another table named vehicle having field - c_id(FK Refers car - id). Now I want to display the FK(c_id) value which is car-type. I've below code in models,

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

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

vehicle model,

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

What 'll be my query for this? I've tried this code, results error.

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

How can I achieve this? Can anybody help me?

like image 279
usertest Avatar asked Oct 20 '25 16:10

usertest


1 Answers

Try this

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

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

The vehicle model

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

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

Eloquent determines the foreign key of the relationship based on the model name. In this case, the Car model is automatically assumed to have a car_id foreign key. If you wish to override this convention, you may pass a second argument to the method

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

To get the Car along with their Vehicle information you can do a query using Eager Loading

$result = Car::with('vehicles')->get();
like image 120
Bivin Avatar answered Oct 23 '25 07:10

Bivin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!