如何 运行 mysql 在 Laravel 中查询

how to run mysql query in Laravel

我想将我的 MySql 查询转换为 Laravel 中的查询,但我真的不知道该怎么做。我不知道如何在 SQL

中重命名 FROM

我的查询如下:

SELECT f2.* FROM formation f2 WHERE f2.theme_id IN 
(SELECT f.theme_id FROM user_formation uf JOIN formation f ON uf.formation_id = f.id WHERE uf.user_id = 2) 
AND f2.id NOT IN 
(SELECT formation_id FROM user_formation WHERE user_id = 2);

我试过类似的方法但是...

$q = Formation::query()
                ->from('formation AS f2')
                ->whereIn('f2.theme_id', function($r)
                {
                    $r->select('f.theme_id')->from('user_formation AS uf')
                    ->join('formation', function($join)
                    {
                        $join->on('uf.formation_id', '=', 'f.id')
                        ->where ('uf.user_id', '=', $id)
                    });
                });

            ->whereNotIn('f2.id', function($s){
                $s->select('formation.id')
                ->from('user_formation')
                ->where('user_id', '=', $id)
            })->get();

感谢您的帮助。

如果你想运行这个原始查询你可以运行:

$res = DB::select('
  SELECT f2.* 
  FROM formation f2 
  WHERE f2.theme_id IN 
    (SELECT f.theme_id FROM user_formation uf JOIN formation f ON uf.formation_id = f.id WHERE uf.user_id = 2) 
    AND f2.id NOT IN 
    (SELECT formation_id FROM user_formation WHERE user_id = 2)');

或者您可以在 laravel 查询生成器 Eloquent ORM 中重写此查询:

Formations::query()
  ->whereIn('formations.theme_id', function($q){
      $user_formations_table = (new UserFormation)->getTable();
      $formation_table = (new Formation)->getTable();
      $q->select('paper_type_id')
        ->from($user_formations_table)
        ->join($formation_table, "$user_formations_table.formation_id", '=', "$formation_table.id")
        ->where("$user_formations_table.user_id", 2);
  })->whereNotIn('formations.id', function($q){
      $user_formations_table = (new UserFormation)->getTable();
      $q->select('formation_id')
        ->where("$user_formations_table.user_id", 2);
  })
  ->get();

Note that I have used models Formations, UserFormation, Formation Because you have used 3 different tables, you should add this models and specify tables to run ORM query

我建议 运行 第一个 RAW 查询,如果不需要 运行 它 Eloquent

希望对您有所帮助

首先,您需要修复代码缩进,以免混淆。其次,你把分号放在了错误的地方。第三,由于变量范围,您需要在函数内部传递 $id

$q = Formation::query()
    ->whereIn('f2.theme_id', function($r) use ($id) {
        $r->select('f.theme_id')->from('user_formation AS uf')
            ->join('formation', function($join) use ($id) {
                $join->on('uf.formation_id', '=', 'f.id')
                ->where('uf.user_id', '=', $id);
            }
        );
    })
    ->whereNotIn('f2.id', function($s) use ($id) {
        $s->select('formation.id')
        ->from('user_formation')
        ->where('user_id', '=', $id);
    })->get();

注意:如果您使用 VSCode,我建议使用 PHP Intelephense,因为它有助于自动完成、语法检查等。