我有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);
我为汽车关系获取null
{"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}]},
答案 0 :(得分:0)
根据我的理解,您正试图通过路线模型访问汽车模型。
我注意到的一些事情可以帮助您找到解决方案。
首先,我认为反向关系应该使用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);
使用正确的关系设置,您很少需要担心数据透视表。如果您要在数据透视表中添加额外信息,可以使用laravel函数来帮助您在文档中执行此操作。