Laravel:加载关系和特定列

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?

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();

You can try like this:

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

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