Laravel 5.5 通过嵌套关系检索 null

Laravel 5.5 retrieving null by nested relation

我有 3 个数据库:

路线: id name

率:

Id
Route_id
Car_id

汽车:

id
name

我的路线模型

public function rates()
{
    return $this->hasMany('App\Rate', 'route_id');
}

我的费率模型

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

现在我需要访问汽车关系,但是当我这样做时

return $this->route->with('from','to','rates.car')->paginate(74);

我得到的汽车关系为空

{"id":1,"from_id":1,"to_id":2,"distance":400,"created_at":null,"updated_at":null,"from":{"id":1,"name":"\u0410\u043a\u043a\u043e","created_at":null,"updated_at":null,"lat":32.93310000000000314912540488876402378082275390625,"long":35.0827000000000026602720026858150959014892578125},"to":{"id":2,"name":"\u0410\u0440\u0430\u0434","created_at":null,"updated_at":null,"lat":31.261399999999998300381776061840355396270751953125,"long":35.21490000000000009094947017729282379150390625},"rates":[{"id":1,"route_id":1,"car_id":1,"rate":1123,"night_rate":1391,"car":null},{"id":5551,"route_id":1,"car_id":2,"rate":1123,"night_rate":1391,"car":null},{"id":11101,"route_id":1,"car_id":3,"rate":1123,"night_rate":1391,"car":null},{"id":16651,"route_id":1,"car_id":4,"rate":1123,"night_rate":1391,"car":null},{"id":22201,"route_id":1,"car_id":5,"rate":1123,"night_rate":1391,"car":null},{"id":27751,"route_id":1,"car_id":6,"rate":1123,"night_rate":1391,"car":null},{"id":33301,"route_id":1,"car_id":7,"rate":1123,"night_rate":1391,"car":null},{"id":38851,"route_id":1,"car_id":8,"rate":1123,"night_rate":1391,"car":null}]},

据我了解,您正在尝试通过路线模型访问汽车模型。

我注意到的一些事情应该可以帮助您找到解决方案。

首先我认为你应该使用 belongToMany() 函数来代替反关系。

public function car() {
    return $this->belongsToMany('App\Car','Rates'); // Perhaps call the table something like routes_cars to more clearly define it's a pivot table
}

接下来我看到您正在尝试在 $this() 的上下文中使用模型函数。我假设你在你的模型中这样做?该逻辑应该在控制器中,这可能会导致一些不良结果,但我不完全确定。此外,使用 with() 时您的参数似乎不正确。您使用在 belongsToMany()

中定义的函数名称
App/Route::with('car')->paginate(74);

通过正确的关系设置,您很少需要担心枢轴 table。如果您要在数据透视表 table 中添加额外信息,文档中有 laravel 函数可帮助您完成此操作。