【问题标题】:Pre-fill database table column field with HTML using Laravel migration使用 Laravel 迁移用 HTML 预填充数据库表列字段
【发布时间】:2021-08-22 04:07:42
【问题描述】:

我使用 Laravel 迁移向数据库表添加了一个新列,如下所示:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddFAQToStoreTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('store', function (Blueprint $table) {
            $table->longText('FAQ')->after('description');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('store', function (Blueprint $table) {
            $table->dropColumn('FAQ');
        });
    }
}

作为 FAQ 的默认值,我希望在运行迁移时为所有商店预填充以下 HTML:

<div><span style="font-weight:600">Can we get our purchase delivered?</span><br/>
Yes, items purchased can be delivered. However, due to COVID-19 restrictions, we are expecting a 3-5 business days' delay.</div>

是否可以添加一个新列并同时使用上面的 HTML 块预先填充它?如果使用数据库播种器是更好的做法,也请提出建议。谢谢

【问题讨论】:

  • 为什么不用php端?

标签: php laravel database-migration


【解决方案1】:

我建议不要使用这种方法,在您的数据库中存储一个简单的段落并将其添加到您的刀片模板中并使用所需的标签,但是如果您坚持并想要插入默认数据,例如 FAQ 或其他东西,没有特定结构的,你应该使用 Laravel Query Builder 添加它们,如下所示:

// define table

   public function up()
    {
        Schema::table('store', function (Blueprint $table) {
            $table->longText('FAQ')->after('description');
        });
    }


// insert some stuff

    DB::table('store')->where('FAQ', '=', '')->update(array('FAQ' => '<div> . . . </div>'));

并在您的刀片模板中使用它。

【讨论】:

  • 谢谢!我不得不稍微调整您的建议以使其对我有用。我不得不执行“更新”,而不是执行“插入”,所以它现在看起来如下 - DB::table('store')->where('FAQ', '=', '')->update (array('FAQ' => '
    . . . .
    '));
  • 哦,太好了...谢谢你让我知道。我根据您的经验更新了我的答案,以便其他人可以使用它!
【解决方案2】:

您可以使用 Seeder 更新新列并执行查询。 1.播种机-Link 2. 在你的迁移文件中执行查询

 public function up()
    {
         Schema::table('store', function (Blueprint $table) {
             $table->longText('FAQ')->after('description');
         });
         $html = '<div><span style="font-weight:600">Can we get our purchase delivered?</span><br/>
Yes, items purchased can be delivered. However, due to COVID-19 restrictions, we are expecting a 3-5 business days' delay.</div>';
         DB::statement('UPDATE store SET FAQ='.$html);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-30
    • 2011-03-06
    • 2012-09-26
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多