我对Laravel有点陌生,所以我希望这个问题很清楚。
我有一个包含Users的表,另一个有Tasks的表。
在我的用户模型中,我有以下内容:
public function tasks() {
return $this->hasMany('App\User' , 'id');
}
我可以执行以下操作从数据库中检索单个用户
$users = \App\User::find(1)->tasks()->paginate();
但是我明白了
{"current_page":1,"data":[{"id":1,"name":"Ed","email":"mail@weqweqeq.com","email_verified_at":null,"created_at":null,"updated_at":null,"tasks":[{"id":1,"name":"Ed","email":"mail@weqweqeq.com","email_verified_at":null,"created_at":null,"updated_at":null}]},{"id":2,"name":"Alyse","email":"mail@rxygewe.com","email_verified_at":null,"created_at":null,"updated_at":null,"tasks":[]}],"first_page_url":"http:\/\/127.0.0.1:8000?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/127.0.0.1:8000?page=1","next_page_url":null,"path":"http:\/\/127.0.0.1:8000","per_page":15,"prev_page_url":null,"to":2,"total":2}
我也尝试过:
$users = \App\User::with(['tasks' => function($q) {
$q->first();
}])->paginate();
但是task属性为空
我的问题是我如何才能获得所有用户,但只有第一个任务才能分页工作?
任务表
1 id(Primary) bigint(20) UNSIGNED No None AUTO_INCREMENT
2 created_at timestamp Yes NULL
3 updated_at timestamp Yes NULL
4 task_name varchar(255) utf8mb4_unicode_ci No None
5 user_id(Index) bigint(20) UNSIGNED No None
答案 0 :(得分:0)
您的模型关系定义不正确。您已将一个用户与许多用户相关联。
https://laravel.com/docs/master/eloquent-relationships#one-to-many
public function tasks() {
// a User ($this) has many Tasks
return $this->hasMany('App\Task');
}
另外,使用->first()
时要小心,因为除非指定,否则不能保证顺序。
$users = \App\User::with(['tasks' => function($q) {
// get the most recently created task
$q->latest()->first();
}])->paginate();