首页 文章

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

提问于
浏览
1

我想在laravel查询构建器中使用where条件创建一个左外连接 . 我有3张 table :

  • user(id,name,..)

  • route(id,name,..)

  • user_route(id,user_id,route_id)

我想选择仅针对特定用户的user_route表中未列出的所有路由 .

我尝试过的:

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

这将不返回任何行 .

$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));
      });

这将返回所有路由,因为它不是外连接 .

还尝试过这样的事情:

$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');

要么

$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));
      });

他们都没有工作 .

我做了一个丑陋的解决方法,我用左连接选择所有路由,在PHP中我删除user_id不为NULL的路由(例如存在) .

有没有人知道如何进行这样的查询而不在SQL中执行并将其传递给Eloquent(或者Laravel的DB插件的名称是什么)?

2 回答

  • 1

    看看Eloquent的 whereDoesntHave() 方法 . 它允许您过滤掉相关表中没有记录的记录 .

    在您的情况下,您希望执行以下操作:对于给定用户,获取与该用户无关的所有路由 . 以下代码应该可以解决问题:

    // $userId contains the ID of the user for which you want to get the unrelated routes
    $routes = Route::whereDoesntHave('users', function($query) use ($userId) {
      $query->where('id', '!=', $userId);
    })->get();
    

    只需确保 Route 模型中定义了 users 关系 .

  • 0

    看起来你从未真正调用过“get”方法 . 试试这个:

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

    ?>

    请注意,您需要根据表格添加正确的密钥 . 如果我们能够看到您的数据结构,这会更容易 .

相关问题