【问题标题】:How insert a query into a database using Laravel?如何使用 Laravel 将查询插入数据库?
【发布时间】:2020-04-28 11:48:03
【问题描述】:

我有这个问题

$data = DB::table('incidencias')
   ->join('clientes_incid', 'clientes_incid.rif', '=', 'incidencias.rif')
   ->select('incidencias.rif')
   ->distinct()
   ->get();

我想将此查询的信息插入我数据库的新表中

我怎么能这样做?有人可以帮助我吗?

【问题讨论】:

标签: laravel laravel-query-builder


【解决方案1】:

您可以创建模型的新实例,附加数据,然后保存。您可以使用关系将数据连接到另一个表。

例子:

$user = new User();
$user->name = "Not set";
$user->email = $email;
$user->password = NULL;
$user->save();

$accounts = new Account();
$accounts->email = $email;
$user->account()->save($accounts);

$userAccount = new UserAccount();
$userAccount->userAccount()->sync([
   $user->id,
   $accounts->id

Laravel 关系: https://laravel.com/docs/5.8/eloquent-relationships#inserting-and-updating-related-models

Laravel 查询: https://laravel.com/docs/5.8/queries#inserts

【讨论】:

    【解决方案2】:

    您有第一个表中的数据,所以您就快到了。根据当前格式,您可以循环遍历它并将insert() 放入新表中。

    一些伪代码:

    foreach ($data as $inData) {
        DB::table('some_new_table')->insert(['column1' => $inData->column1, 'column2' => $inData->column2, ...]);
    }
    

    【讨论】:

    • 我是这样做的: public function index() { $data = DB::table('incidencias') ->join('clientes_incid', 'clientes_incid.rif', '=', ' incidencias.rif') ->select('incidencias.rif') ->distinct() ->get();返回视图('ATC.index',紧凑('数据')); foreach ($data as $inData) { DB::table('clientes_view') ->insert(['rif' => $inData->rif]); } } 但没有在我的数据库中填写表格...我该如何修复它...谢谢!!
    【解决方案3】:

    您可以针对这种情况在数据库中创建一个视图。 创建一个迁移并在 up 方法中编写您的 sql,它将由您的数据库自动填充。

      public function up()
      {
        DB::statement("
          CREATE VIEW clients_view AS
          (
             // wirte your sql command here
          )
        ");
      }
    

    【讨论】:

      【解决方案4】:

      你可以这样插入数据

      DB::table('table')->insert($data);
      

      插入接受数组

      【讨论】:

        【解决方案5】:
         public function store(Request $request)
            {
                $this->validate($request,[
                    'name' => 'required'
                ]);
                $category = new Category();
                $category->name = $request->name;
                $category->slug = str_slug($request->name);
                $category->save();
                Toastr::success('Category Successfully Saved','Success');
                return redirect()->route('admin.category.index');
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-02-12
          • 2018-08-06
          • 1970-01-01
          • 2023-03-27
          • 2019-09-26
          • 2018-01-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多