Adam
Adam

Reputation: 29089

Laravel: Load relationships and specific columns

I have two tables User and Car. One user may have a car.

I have a relation set like this:

public function car()
{
    return $this->hasOne('App\Car');
}

I want to fetch the users with a car, but only select the name of the user and the color of the car.

If I try

App\User::with('car:color')->select('name')->first()->toArray();

then I do not get the car color. That is the result:

array:1 [▼
  0 => array:2 [▼
    "name" => "Max Mustermann"
    "car" => []
  ]
]

Is it possible to only get the name of the user and the color of the car?

Upvotes: 0

Views: 143

Answers (3)

Christoph Winkler
Christoph Winkler

Reputation: 6418

It fails because the User Table has no color Column. You have to access the relation to get the color.

$user = User::has('car')->first();

print $user->car->color;

AFAIK you won't be able to fetch just the two fields with Eloquent Relations. One way to achieve this would be using Query Builder:

DB::table('users')
    ->join('cars', 'users.id', '=', 'cars.user_id')
    ->select('users.name', 'cars.color')
    ->get();

Upvotes: 1

Richie
Richie

Reputation: 1439

This is the correct way.

$users = User::with('car.color')->select('name')->get();

and then you can display them as:

foreach($users as $user){
     echo $user->name . " owns a " . $user->car->color . " car.";
}

Upvotes: 1

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

You can try like this:

User :: Select("*")->with("car")->get();

Upvotes: 1

Related Questions