代码之家  ›  专栏  ›  技术社区  ›  Patrick

基于两个不同因素获取数据库中最新输入的算法

  •  0
  • Patrick  · 技术社区  · 9 年前

    我有一个建立在laravel上的网站。网站由用户组成,用户可以互相关注。 Users 可以 Shoutouts (就像一条推文),并且相互关注的用户应该能够看到这些。我有一个 User 数据库中的表,以及 Shoutout 表,和 Follow 桌子

    由于它是由i Laravel制作的,用户有一个 hasMany 与Shoutout和下表的关系。

    因此,当用户登录时,我想获取用户正在跟踪的所有人。我通过以下方式做到这一点:

    $following = Follow::whereUser_id($user->id)->get();
    

    然而,我现在如何获得 叫喊 来自中的用户 $following ,按照从创建shoutout开始的顺序,所以我可以在我的视图中执行foreach($shoutouts作为$shoutout)? 其想法是,用户可以看到用户跟踪的人的最新叫喊。

    如果我做了这样的事情:

    $following = Follow::whereUser_id($user->id)->get();
    
    foreach($following as $follow) {
        $shoutouts = $shoutouts . Shoutout::whereUser_id($follow->user_id)->get();
    }
    

    我会以不正确的顺序获取它们,因为这会给我一个特定用户的所有喊叫声,但我希望以降序获取它们,因此用户首先看到最新的喊叫声。

    感谢所有的帮助。

    2 回复  |  直到 9 年前
        1
  •  3
  •   Amit Gupta    9 年前

    您可以使用 join 作为:

    假设你有 followed_user_id 在你 Follow 桌子

    $shoutouts = Shoutout::join('follow', 'shoutout.user_id', '=', 'follow.followed_user_id')
                        ->where('follow.user_id', $user->id)
                        ->select(''shoutout.*'')
                        ->orderBy('shoutout.created_at', 'desc')
                        ->get()
    
        2
  •  0
  •   Eric Tucker    9 年前

    你在找什么 https://laravel.com/docs/5.3/eloquent-relationships#eager-loading 在您关注的用户的呼喊声中。如果您正确定义了关系,您应该能够:

    $following = Follow::whereUser_id($user->id)->with('shoutouts')->get();
    

    然后通过以下方式访问用户的呼喊:

    foreach($following as $follow) {
        $shoutouts = $follow->shoutouts;
        //Do Something With The Collection Of Shoutouts
    }
    

    更新 为了获得他们关注的用户的呼喊声,您可以定义 hasManyThrough 在用户表上:

    public function followerShoutouts()
    {
        return $this->hasManyThrough(Shoutout::class, Follow::class, 'user_id', 'user_id_being_followed');
    }
    

    然后你可以做:

    $shoutouts = User::with(['followerShoutouts' => function($query) {
        return $query->orderBy('created_at', 'desc');
    }])->find($userId);
    
    推荐文章