我正在使用Laravel和Vue建立一个论坛网站。
我有三个表:论坛、帖子和用户。 一个论坛可以有多个帖子,每个帖子都有一个创建帖子的用户。
当用户点击一个论坛时,我想使用分页方法显示该论坛的最新 10 个帖子。
论坛.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Forum extends Model {
use HasFactory;
protected $table = 'forums';
protected $guarded = [];
/**
* Get the forum posts
* @return IlluminateDatabaseEloquentRelationsHasMany
*/
public function posts() {
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
}
后.php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Post extends Model {
use HasFactory;
protected $table = 'posts';
protected $guarded = [];
/**
* Get the post's user
* @return IlluminateDatabaseEloquentRelationsBelongsTo
*/
public function user() {
return $this->belongsTo(User::class);
}
}
用户.php
<?php
namespace AppModels;
use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
class User extends Authenticatable {
use HasFactory, Notifiable;
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the user posts
* @return IlluminateDatabaseEloquentRelationsHasMany
*/
public function posts() {
return $this->hasMany(Post::class);
}
}
在这里,我与用户一起检索论坛帖子。
论坛服务.php
<?php
namespace AppServices;
use AppModelsForum;
class ForumService {
public static function getForumPosts($forumId) {
$forum = Forum::with('posts.user')->find($forumId);
dd($forum);
}
}
但是,我只想检索 10 个帖子并获取每个帖子的用户,那么如何在关系中做到这一点?帖子是分页的,但是我现在如何获得发布用户?因为点语法适用于用户,所以我对用户进行分页,而不是帖子。
论坛服务.php
<?php
namespace AppServices;
use AppModelsForum;
class ForumService {
public static function getForumPosts($forumId) {
$forum = Forum::with(
[
'posts' => function ($query) { // How do I get the post user?
return $query->paginate(10);
}
]
)->find($forumId);
dd($forum);
}
}
只需将with
方法添加到您创建的函数的查询范围内即可。
$forum = Forum::with(
[
'posts' => function ($query) {
// returns posts with user
return $query->with('user')->paginate(10);
}
]
)->find($forumId);
现在,您可以使用$forum->posts[0]->user
访问第一个用户,该用户不会查询数据库,但会预取用户并将其填充到分页器集合中。
由于您已经拥有论坛的 ID,因此您只能检索属于该Forum
的帖子并像这样对它们进行分页
public static function getForumPosts($forumId) {
return Forum::find($forumId)->posts()->paginate(10);
}
如果你想急切加载Post
创建者,你可以像这样执行
public static function getForumPosts($forumId) {
return Forum::find($forumId)->posts()->with(['user'])->paginate(10);
}