为shared_posts
创建一个多对多的关系:https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
下面是一个未经测试的例子。
public function sharedPosts()
{
//Probably can be shorter, look at the laravel docs.
return $this->belongsToMany('App\Post', 'post_shares', 'post_id', 'user_id');
}
现在你有2个系列的两个模型。一个与用户帖子和一个与用户共享帖子。然后你可以合并这两个集合:
$posts->merge($sharedPosts)->sortBy('created_at');
唯一的问题是,你不能告诉哪些帖子是共享的,什么不是。但是,这可以通过以下功能
public function getAllPostsAttribute()
{
$posts = $this->posts()->selectRaw('"user_post" AS type')->get();
$sharedPosts = $this->sharedPosts()->selectRaw('"shared_post" AS type')->get();
return $posts->merge($sharedPosts)->sortBy('created_at');
}
现在,您可以调用用户的allPosts
属性,并得到所有帖子和分享的职位是固定的。您可以在帖子后区分2的type
属性。
我还没有测试过任何东西,所以请让我知道是否有错误。
另一种方法可能是一个mysql联盟。
阅读laravel中的'eager loading' https://laravel.com/docs/5.4/eloquent-relationships#eager-loading –