【问题标题】:SQL subqueries to laravel到 laravel 的 SQL 子查询
【发布时间】:2020-06-15 15:43:17
【问题描述】:

我试图将一个查询传递给 laravel,但我做不到。这是查询

SELECT * 
FROM installations 
WHERE id = 1 AND
(SELECT eliminado from projects where id = installations.project_id) = 0;

我尝试过类似的东西

$project = installations::where([
          ['id',$id],
          [function ($query) use ($projects) {
              $query -> select('eliminado')
                     -> from('projects')
                     -> where('id', $projects[0]->project_id);
            }, 0]])->get();

$projects =  DB::table('installations')
        ->select('*')
        ->where([
          ['id', 'LIKE', $id],
          [(function($query) use ($projects) {
            $query -> select('*')
                   -> from('projects')
                   -> where('id', $projects[0]->project_id);
            }), 'LIKE', '0']
          ])
    ->get();

但它仍然无法正常工作......有人可以帮助我吗?谢谢你

【问题讨论】:

    标签: mysql sql laravel eloquent subquery


    【解决方案1】:

    我认为你可以使用这样的东西:

    $project = installations::where('id', $id)
          ->whereRaw('(SELECT eliminado from projects where id = installations.project_id) = ?', [0])
          ->get();
    

    【讨论】:

      【解决方案2】:

      Installation 模型上使用关系project,您可以这样做。

      $intallation = Installation::whereHas('project', function($query) {
          $query->where('eliminado', '=', 0);
      })->find($id);
      

      project 关系应该是belongsTo

      安装.php

      public function project()
      {
          $this->belongsTo(Project::class);
      }
      

      【讨论】:

        【解决方案3】:

        你可以这样做..

        SELECT * 
        FROM installations ins
        WHERE id = 1 AND EXISTS
        (SELECT 1 from projects p where p.id = ins.project_id AND p.eliminado =0);
        

        【讨论】:

          猜你喜欢
          • 2018-05-31
          • 1970-01-01
          • 2020-03-25
          • 2020-04-19
          • 2021-07-27
          • 2014-07-12
          • 2015-02-13
          • 2018-04-28
          • 2018-10-02
          相关资源
          最近更新 更多