首页 > 解决方案 > 调用未定义的关系 - Laravel

问题描述

我正在使用最新Laravel的 . 我在控制器中也有从关系表中选择表和数据的方法:

$cars= Car::with(array('car_photos'=>function($query){
    $query->select('id');
}))->get();

Cars有很多照片。汽车模型:

public function photos(){
    return $this->hasMany('App\Models\CarPhoto');
}

CarPhoto模型:

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

我可以选择汽车的所有照片:

$car= Car::where('id', $id)->first();
$photos = $car->photos;

但是$cars= Car::with....,我得到:

调用模型 [App\Models\Car] 上的未定义关系 [car_photos]。

标签: laravellaravel-5

解决方案


关系名称不是类名称:

  $cars= Car::with(array('photos'=>function($query){
        $query->select('id');
    }))->get();

推荐阅读