【发布时间】:2018-09-16 09:39:07
【问题描述】:
在我的应用中,我有多个关系。用户有很多事件。许多活动有许多参与者。
例如事件模型:
public function participants()
{
return $this->belongsToMany('App\Participant');
}
public function user()
{
return $this->belongsTo('App\User');
}
我想获取所有用户事件参与者并对他们进行分页。
$participants = $user->events->participants;
这显然不起作用,这就是为什么我要尝试这样的事情
$events = $user->events;
$participants = [];
foreach ($events as $event) {
$participants[] = $event->participants;
}
return $participants;
这适用于获取数据数组,但我无法使用 DB 分页对其进行分页,因为它是一个数组。
有没有另一种方法可以让所有参与者建立更深层次的关系?或者我还能如何使用 laravel 或 lumen 分页?
编辑:添加迁移
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
...
});
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
...
});
Schema::create('participants', function (Blueprint $table) {
$table->increments('id');
...
});
Schema::create('event_participant', function (Blueprint $table) {
$table->integer('event_id');
$table->integer('participant_id');
});
编辑 2:我的解决方案: 使参与者排列 Laravel 集合并添加宏方法进行分页,如回答这里https://laracasts.com/discuss/channels/laravel/how-to-paginate-laravel-collection
【问题讨论】:
-
您要对参与者进行分页吗?
-
@HaiderAli 是的,但仅来自用户事件。
-
return $this->hasManyThrough('App\Participant', 'App\Event');这实际上不起作用,因为我在参与者和事件之间有数据透视表。如何让它引用数据透视表而不是在 Participants 表中搜索 event_id?
标签: php laravel eloquent lumen