dongsibao8977 2017-04-18 02:56
浏览 27

如何从Laravel Eloquent中的另一个表中检索行?

I have 3 tables: posts, votes and users. I have written a neat code with Eloquent to retrieve just the posts where the user has not voted yet on.

$posts = Post::whereDoesntHave("votes")
                    ->where('user_id', '=', $user_id)
                    ->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
                    ->take(20)
                    ->get();

return response()->json(['posts' => $posts])->withCallback($request->input('callback')); 

But also I want to retrieve user name from table users. I want to pass the data with json.

If I try to do it with query builder, it is hard to eliminate posts that have been voted already by the user.

  • 写回答

1条回答 默认 最新

  • drd43058 2017-04-18 03:07
    关注

    You can do a join manually to the user table

    $posts = Post::join('users', 'users.id', '=', 'posts.user_id')
                    ->whereDoesntHave("votes")
                    ->where('user_id', '=', $user_id)
                    ->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
                    ->take(20)
                    ->get();
    

    Or you could define a relationship in the Post model class.

    public function user()
    {
       return $this->belongsTo('App\User');
    }
    

    Then you use with('user') to retrieve data from user table.

    $posts = Post::with('user')
                    ->whereDoesntHave("votes")
                    ->where('user_id', '=', $user_id)
                    ->whereBetween('posts.created_at', array(Carbon::now()->subHours(48), Carbon::now()))
                    ->take(20)
                    ->get();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集