如何在Laravel 5.8中获得关注的用户帖子

问题描述 投票:0回答:2

我在Laravel 5.8项目中有两个模型,下面两个模型类中都显示了关系。如何仅使用一个sql查询就可以获取与我关注的每个用户相关的每个帖子记录?我可以使用Eloquent Query Builder还是需要Raw SQL Query?有人可以告诉我要执行的SQL查询吗?

抱歉,我不知道要在标题中加上什么标题。

提前感谢!

用户类别。

class User extends Authenticatable implements MustVerifyEmail{

   use Notifiable, MessageAccessible, TagsCreator;

   /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
   protected $fillable = [
      'name',
      "lastname",
      "country",
      "city",
      "phone_number",
      'e_mail',
      'password',
      "role_id",
      "profile_picture",
      "occupation",
      "biography"
   ];

   /**
    * 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'];

   public function posts(){
      return $this->hasMany(Post::class);
   }

   public function followers(){
      return $this->belongsToMany(User::class, 'follower_followed', 'followed_id', 'follower_id');
   }

   public function following(){
      return $this->belongsToMany(User::class, 'follower_followed', 'follower_id', 'followed_id');
   }
}

邮政课。

class Post extends Model{

   /**
    * The attributes that are mass assignable.
    *
    * @var array
    */
   protected $fillable = [
      'user_id',
      "post_permission_id",
      "title",
      "content",
      "likes",
      "dislikes"
   ];

   public function user(){
      return $this->belongsTo(User::class);
   }
}
sql laravel eloquent laravel-5.8 laravel-query-builder
2个回答
1
投票

我认为您需要做的是这个。

[不确定,但是在某些Laravel版本中,您必须在此处使用select而不是pluck。此版本适用于5.6

$posts = Post::whereIn(user_id, User::find($user_id)->followers->pluck('id'))->get();

那么您可能想按关注者订购帖子

$posts = Post::whereIn('user_id', User::find($user_id)->followers->pluck('id'))->orderBy('user_id', 'ASC')->get();

这里是whereIn的文档,向下滚动一点,在whereIn上没有直接锚定:-)


1
投票

找到/选择用户后,您可以通过以下方式获得相关信息:

$user = Auth::user(); // selecting the logged in user
$user->posts;

为此,您必须在user_id表中具有posts列。

如果您想拥有所有用户及其帖子,则可以执行以下操作:

$usersWithPosts = User::with('posts')->get();

如果您只希望本质上至少有一个帖子的用户执行此操作,这将返回所有用户(无论他们是否有任何帖子):

$usersWithPosts = User::has('posts')->get();
© www.soinside.com 2019 - 2024. All rights reserved.