【发布时间】:2014-11-21 15:37:03
【问题描述】:
我正在使用 Laravel 4.2 构建一个应用程序。我有units 的模型和users 的另一个模型和数据透视表user_units。此应用程序中的每个用户都可以选择一个单元并将其添加到他最喜欢的列表中,然后他可以将该单元与他的信息一起作为广告发布。
我要选择所有用户发布的所有单元
user_units(数据透视表)具有以下列:
id
user_id
unit_id
publish
adtype
addinfo
created_at
updated_at
在模型上使用关系方法
public function users() {
return $this->belongsToMany('User', 'user_units')
->withPivot('id','publish', 'adtype', 'addinfo');
}
public function units() {
return $this->belongsToMany('Unit', 'user_units')
->withPivot('id','publish', 'adtype', 'addinfo');
}
我的查询选择所有用户发布的所有单位
// Get all published units by users for sale.
$users = User::all();
$publishedSaleUnits = [];
foreach($users as $user){
$userUnits = $user->units()->orderBy('adtype', 'desc')->get();
if(count($userUnits)){
foreach($userUnits as $unit){
if($unit->pivot->publish == 1 && $unit->unit_purpose_id == 1){
if( $unit->pivot->adtype ){
//push all featured ads onto the beginning of array
array_unshift($publishedSaleUnits, $unit);
}else{
//push all normal ads onto the end of array
array_push($publishedSaleUnits, $unit);
}
}
}
}
}
现在我得到了结果,但我不能对结果使用分页,因为它是一个对象数组。
那么有没有更好的解决方案来让用户通过分页获取所有已发布的单元?
【问题讨论】:
标签: laravel-4 pagination pivot-table