我想对 2 个模型进行分页:Trip
其中 hasMany
PartialTrip
。
旅行
模型:
public function PartialTrips()
{
return $this->hasMany('PartialTrip', 'main_trip_id');
}
棘手的部分是,在包含查询信息的对象中,我希望将每个 PartialTrip
放在拥有它的 Trip
下。因此,例如:查询 Trip
-> 查询 PartialTrip
,其中 whereMainTripId
= 当前 Trip
的 id -> 分页(5)。
这样,当我列出它们时,部分行程将不会位于数组对象的末尾,而是每个行程都会直接位于其父行程之后。
更新
我正在这样做(只是为了测试 ::with('PartialTrips')
是否有效:
$trips = Trip::with('PartialTrips')
->select('id', 'driver_user_id', 'route_from', 'route_to', 'start_date')
->get();
var_dump(count($trips));
它返回我的行程
数量(我计算了我有多少行程和部分行程在数据库中)。
->toSql()
产生以下结果:
"select 'id', 'driver_user_id', 'route_from', 'route_to', 'start_date' from 'trips'"
所以我猜 ::with('PartialTrips')
在这种情况下并不起作用......
最佳答案
这是 trip_id
的答案
Take note that Eloquent assumes the foreign key of the relationship based on the model name.
更多详细信息:http://laravel.com/docs/4.2/eloquent#one-to-one
当您使用hasMany
关系没有特定的外
键时,模型假设使用trip_id
作为外键(表名+ ID)。无论如何你可以覆盖它。你的模型可能看起来像
//Trip model
public function PartialTrips()
{
return $this->hasMany('PartialTrip', 'main_trip_id'); // second parameter is your foreign key
}
更多详情:http://laravel.com/docs/4.2/eloquent#one-to-many
通过将 $trips
变量传递给 View 并像这样渲染它们,您可以获取所有 trips
和 partial trips
@foreach ($trips as $trip)
<div> Your trip id: {{ $trip->id }}</div>
<div> -- Partial Trips </div>
@foreach ($trip->partialTrips as $partialTrip)
<div> Partial trip id: {{ $partialTrip->id }}</div>
@endforeach
@endforeach
注意:当您使用 with()
(热切加载)时,$partialTrips
将嵌套在 $trips
内。这就是为什么在使用 count($trips) 时只能得到 $trips 的数量。但是您可以使用上面的代码获取partialTrips。
关于php - 对相关模型进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879047/