我正在构建一个应用程序,Laravel作为我的前端,Angular作为我的后端。我正在实施的帖子和评论用户的喜欢系统。我有一个多态关系与我喜欢的系统,因为用户可以喜欢的帖子+评论。我的模型是这样的:
像模型
class Like extends Model
{
public function likeable()
{
return $this->morphTo();
}
}
Post模型class Post extends Model {
public function user()
{
return $this->belongsTo('App'Models'User', 'author_id');
}
public function likes()
{
return $this->morphMany('App'Models'Like', 'likeable');
}
}
注释模型
class Comment extends Model
{
public function likes()
{
return $this->morphMany('Like');
}
}
我不知道该怎么做。当我加载一篇文章或评论时,我想检索文章的详细信息(我已经可以检索到)+点赞数和谁喜欢它。我如何热切加载"喜欢"的数据与帖子?我应该在这里使用多态关系吗?提前感谢!
我的Like表是这样的:
Schema::create('likes', function(Blueprint $table) {
$table->increments('id');
$table->integer('user_id'); // User who does the liking
$table->integer('likeable_id'); // User whose Comment/Post is liked
$table->string('likeable_type'); // Item that is being liked
// Could be Comment or Post (Models)
$table->timestamps();
});
这也是我目前正在调查的事情。在源代码中(乍一看),它说它不会在急于加载时加载morphTo
,它只是传递一个虚拟查询。
至于Post
或Comment
侧的动态加载,您应该没问题,即
$posts = Post::with('likes')->get();
$comments = Comment::with('likes')->get();
此外,由于您只需要计数而不是每行喜欢,因此这样的内容值得查看。
希望这对你有帮助!