【问题标题】:Create a Insert... Select statement in Laravel在 Laravel 中创建插入...选择语句
【发布时间】:2014-10-21 10:03:29
【问题描述】:

我需要将此查询转换为 Laravel,但在尝试使用 Laravel 的 Eloquont ORM 或查询创建插入...选择语句时遇到问题。我不确定如何创建此查询。

Insert into Demand (Login, Name, ApptTime, Phone, Physician, Location, FormatName, FormatDate, FormatTime, ApptDate, FormatPhone, cellphone)
Select Login, Name, ApptTime, Phone, Physician, Location, FormatName, FormatDate, FormatTime, ApptDate, FormatPhone, cellphone from " . [dbname] . "
    Where " . $where_statement

如何使用 Laravel 的 ORM 创建这个查询?

编辑:我不确定这是否清楚,但我正在考虑 1 个查询,就像他们在这里做的 http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

【问题讨论】:

  • 请阅读文档,这可能会更有帮助:laravel.com/docs/eloquent
  • 我浏览了文档,并尝试了不同的链。但我仍然不确定如何将其创建为 ONE 查询而不是 2。
  • Eloquent 并不是真的要处理这样的事情。你可以把查询放在DB::statement()中。
  • 是的,我最终将其分为 2 个查询。

标签: php mysql laravel


【解决方案1】:

没有办法在一个查询中执行此操作(除非您使用的是 Laravel 5.7),但是我遇到了同样的问题并想确保我可以继续使用我使用 QueryBuilder 构建的某个选择。

那么你可以做些什么,保持一半的干净并重用之前构建了一个 select 语句的功能,是这样的:

/**
 * Wherever your Select may come from
 **/
$select = User::where(...)
                  ->where(...)
                  ->whereIn(...)
                  ->select(array('email','moneyOwing'));
/**
 * get the binding parameters
 **/ 
$bindings = $select->getBindings();
/**
 * now go down to the "Network Layer"
 * and do a hard coded select
 */
 $insertQuery = 'INSERT into user_debt_collection (email,dinero) '
                . $select->toSql();
    
 \DB::insert($insertQuery, $bindings);

更新 Laravel 5.7

从 Laravel 5.7.17 开始,您可以使用 ->insertUsing()。有关详细信息,请参阅here。感谢@Soulriser 指出这一点。

所以上面的查询应该是这样的:

DB::table('user_debt_collection')->insertUsing(['email','dinero'], $select);

【讨论】:

  • 这真是太棒了。
  • 使用 Laravel 5.7,您可以通过以下方式简化事情:DB::table('user_debt_collection')->insertUsing(['email','dinero'], $select);
  • 谢谢@soulriser,我已经相应地更新了答案。
  • 如果我们希望将一些静态字符串作为列名,语法会怎样?
  • 不确定您的意思是 Sandeep 吗?你的意思是这样的? DB::table('user_debt_collection')->insertUsing([YourClass:COLUMN_NAME,YourClass::OTHER_COLUMN_NAME], $select); ??
【解决方案2】:

你可以使用:

DB::insert("insert into contacts(contact_id,contact_type,account_id,created_at,updated_at) select f.id,'App\\Friend',f.account_id,f.created_at,f.updated_at from friends as f where f.id=?",[16]);

【讨论】:

    【解决方案3】:

    我使用了 DB::statement("...");

    DB::statement("INSERT INTO table (SELECT)");
    

    【讨论】:

      【解决方案4】:

      在 Laravel 5.5 中,我创建了一个辅助函数来更轻松地执行:

      class QueryHelper
      {
      
          /**
           * @param string $model
           * @param array $columns
           * @param Builder $select
           * @return bool
           */
          public static function insertFromSelectStatement($model, $columns, $select)
          {
              /** @var \Illuminate\Database\Query\Builder $query */
              $query = (new $model)->getQuery();
              $sql = "insert into {$query->from} (". implode(', ', $columns) .") {$select->toSql()}";
              return $query->getConnection()->insert($sql, $select->getBindings());
          }
      }
      

      例如:

      $notification = Notification::create([
          'title' => 'this is title',
          'message' => 'this is message',
      ]);
      $now = DB::raw("'". Carbon::now()->toDateTimeString() ."'");
      $selectActivatedUsers = User::select('id', $notification->id, $now, $now)->where('status', '=', 'activated');
      // insert notifications to activated users
      QueryHelper::insertFromSelectStatement(UserNotification::class, ['user_id', 'notification_id', 'created_at', 'updated_at'], $selectActivatedUser);
      

      【讨论】:

        【解决方案5】:

        试试这个

        DB::table(table2)
            ->insert(
                (array) DB::table(table1)
                    ->where('column', '=', $variable)
                    ->select('column1','column2')
                    ->first()
            );
        

        【讨论】:

          【解决方案6】:

          首先,您需要为Demand 创建一个模型,然后您可以使用:

          $demand = new Demand;
          $demand->Login = $login;
          $demand->Name = $name;
          [...]
          $demand->save(); // <~ this is your "insert" statement
          $id = $demand->id;
          

          然后对于您的 select 语句,您可以执行类似于以下选项的操作:

          $demand = Demand::find($id); // will be similar to: SELECT * FROM Demand WHERE `id` = '$id';
          $demand = Demand::where('id', $id)->get(); //same as above
          $demand = Demand::where('id', $id)->get(array('Login', 'Name')); // will be similar to: SELECT `Login`, `Name` FROM Demand WHERE `id` = '$id';
          

          手册herehere中有更多信息

          【讨论】:

          • select 语句是插入的一部分。我已经阅读了文档,但我没有看到如何做这样的事情:dev.mysql.com/doc/refman/5.0/en/insert-select.html 在 Laravel 中使用一个查询就没有办法做到这一点吗?我知道我会如何在 2 内完成,但是这需要一分钟。我想知道是否已经构建了一些东西来创建这个查询。
          • 我认为你不能在 Eloquent ORM 中做到这一点......但我可能是错的
          • 我一直没能找到引发这个问题的方法。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-31
          相关资源
          最近更新 更多