【问题标题】:Database Seeder not inserting correct data in Laravel数据库播种器未在 Laravel 中插入正确的数据
【发布时间】:2020-08-02 17:55:46
【问题描述】:

我需要在 SqLite 数据库中播种 Reg-Ex 模式。我正在使用 Laravel 7。 这是我的播种机:

<?php
use App\PhoneValidetionRules;
use Illuminate\Database\Seeder;

class PhoneValidetionRulesSeeder extends Seeder
{
public function run()
{
    $rules = '
    {
        "iPhone": "\\biPhone\\b|\\biPod\\b",
        "BlackBerry": "BlackBerry|\\bBB10\\b|rim[0-9]+|\\b(BBA100|BBB100|BBD100|BBE100|BBF100|STH100)\\b-[0-9]+",
        "HTC": "HTC|HTC.*(Sensation|Evo|Vision|Explorer|6800|8100|8900|A7272|S510e|C110e|Legend|Desire|T8282)|APX515CKT|Qtek9090|APA9292KT|HD_mini|Sensation.*Z710e|PG86100|Z715e|Desire.*(A8181|HD)|ADR6200|ADR6400L|ADR6425|001HT|Inspire 4G|Android.*\\bEVO\\b|T-Mobile G1|Z520m|Android [0-9.]+; Pixel",
        "Nexus": "Nexus One|Nexus S|Galaxy.*Nexus|Android.*Nexus.*Mobile|Nexus 4|Nexus 5|Nexus 6"
    }';
    $data = [];
    foreach (json_decode($rules, true) as $key=>$value){
        $data[] = [
            'name' => $key,
            'regex' => $value
        ];
    }
    PhoneValidetionRules::insert($data);
}
}

当我播种时,所有\b都转换为\x08。这是数据库:

这是表格蓝图:

Schema::create('phone_validetion_rules', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('regex');
    });

如果我手动从 PhpStorm 更新正则表达式,它会正确插入。 如何使用 Laravel Seeder 将 Reg-Ex 插入数据库?

【问题讨论】:

    标签: php database laravel sqlite eloquent


    【解决方案1】:

    为什么不用json_encode() 像这样插入它们

    'regex' => json_encode($value)
    

    如果这是您要查找的内容,数据将像 "\biPhone\b|\biPod\b" 一样插入。

    【讨论】:

    • 为一个好技巧点赞。但这不是我需要的答案。为什么它转换 \b 被转换为 \x08 ?使用 larael 模型将 Reg-Ex 上传到数据库的确切方法是什么? Raw Sql 也可以做到这一点。但我不想在我的项目中编写原始 Sql。
    • 这不起作用。对于json_decode(PhoneValidetionRules::find(5)-&gt;regex),输出为iPhone|iPodprint_f"\x08iPhone\x08|\x08iPod\x08"dd
    • 首先,您不需要json_decode(PhoneValidetionRules::find(5)-&gt;regex) 来获取正则表达式值,您可以执行PhoneValidetionRules::find(5)-&gt;regex 输出将是"\biPhone\b|\biPod\b" 以删除额外的",您可以执行str_replace("\"", "", PhoneValidetionRules::find(5)-&gt;regex),您将获取\biPhone\b|\biPod\b"
    • 第二,为什么 \b 转换为 \x08 因为这是 json_decode() 行为,它将一些特殊字符转换为 unicode,你必须避免在你的字符串中使用这些特殊字符,你在这里阅读更多json.org/json-en.html
    猜你喜欢
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    • 2015-09-25
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多