[英]Eloquent Polymorphic Relations Eager Loading
I'm building an app with Laravel as my front end and Angular as my back end. 我正在构建一个应用程序,其中Laravel作为前端,而Angular作为后端。 I'm implementing a Like system on posts and comments users make.
我正在对用户发表的帖子和评论实施Like系统。 I have a polymorphic relationship with my like system because users can like posts + comments.
我与喜欢系统有多态关系,因为用户可以喜欢帖子和评论。 My Models look like this:
我的模型如下所示:
Like Model 喜欢模特
class Like extends Model
{
public function likeable()
{
return $this->morphTo();
}
}
Post Model 邮政模型
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');
}
}
Comment Model 评论模型
class Comment extends Model
{
public function likes()
{
return $this->morphMany('Like');
}
}
I'm confused how to go about this. 我很困惑如何去做。 When I load a post or a comment, I want to retrieve the post details (which I can already retrieve) + the like count and who's liked it.
当我加载帖子或评论时,我想检索帖子的详细信息(我已经可以检索到)+喜欢计数和喜欢它的人。 How do I eager load the 'Like' data with the post?
我如何急于在帖子中加载“喜欢”数据? Should I even use Polymorphic relations here?
我是否应该在这里使用多态关系? Thanks in advance!
提前致谢!
My Like table looks like this: 我的“喜欢”表如下所示:
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();
});
This is something I'm also looking into at the moment. 我目前也在研究这一点。 In the source code (at first glance) it says that it doesn't load a
morphTo
on an eager load, it just passes a dummy query. 在源代码中(乍一看),它说它不会在急切加载时加载
morphTo
,而只是传递一个伪查询。
As far as eager loading from the Post
or Comment
side of things you should be fine ie 至于渴望从
Post
或Comment
方面加载,您应该没问题,即
$posts = Post::with('likes')->get();
$comments = Comment::with('likes')->get();
Further more, as you only need the count and not each row of likes something like this would be worth looking at. 进一步,因为你只需要计数,而不是喜欢像每行这将是值得期待的。
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.