doudang4857 2016-10-26 21:03
浏览 49

Laravel查询构建器将外部联接留在哪里

I would like to make a left outer join with laravel query builder with a where condition. I have 3 tables:

  • user (id, name, ..)
  • route (id, name, ..)
  • user_route (id, user_id, route_id)

I want to select all routes which aren't listed in the user_route table only for the specific user.

What I've tried:

$q = DB::table('route')
    ->join('user_route', 'route.id', '=', user_route.route_id', 'left outer')
    ->where('user_route.user_id', '!=', $filter->user);

This will return no rows.

$q = DB::table('route')
->leftJoin('user_route', function($join) use ($filter)
      {
           $join->on('route.id', '=', 'user_route.route_id')
                ->where('user_route.user_id', '=', DB::raw($filter->user));
      });

This will return all the routes as it is not an outer join.

Also tried something like this:

$q = DB::table('route')
->join('user_route', function($join) use ($filter)
      {
           $join->on('route.id', '=', 'user_route.route_id')
                ->where('user_route.user_id', '=', DB::raw($filter->user));
      }, 'left outer');

or

$q = DB::table('route')
->join('user_route', function($join) use ($filter)
      {
           $join->on('route.id', '=', 'user_route.route_id', 'left outer')
                ->where('user_route.user_id', '=', DB::raw($filter->user));
      });

None of them worked.

I've made an ugly workaround, where I pick all routes with left join, and in PHP I delete routes where user_id is not NULL (eg. exists).

Does anyone know how to make such query without doing it in SQL and passing it to the Eloquent (or what is the name of the DB plugin for Laravel)?

  • 写回答

2条回答 默认 最新

  • doushi1510 2016-10-26 21:40
    关注

    It looks like you never actually call the "get" method. Try this:

    <?php
    
    $userid = 10;
    $result = DB::table('route')
    ->join('user_route', 'route.id', '=', 'user_route.route_id')
    ->select('*')
    ->where('user_route.user_id', '=', $userid)
    ->get();
    

    ?>

    Note you will need to add the correct keys based on your table. This would be easier if we could see your data structure.

    评论

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存