gpt4 book ai didi

mysql - 在 Mysql 中创 build 置表并在 laravel 中使用 eloquent 获取

转载 作者:行者123 更新时间:2023-11-29 17:17:13 25 4
gpt4 key购买 nike

我想创建一个包含 2 列(设置、值)的设置表,设置将包含诸如 SITE_NAME 之类的内容,值将是诸如“Facebook”或“Youtube”之类的值。这将保存网站名称、 Logo url 等。我将如何创建它,最重要的是,我将如何在没有 id 字段的情况下使用 Laravel eloquent 获取信息。

最佳答案

要事第一。

您的表需要一个主键。根据您的示例,这将是一个 varchar 字段吗? MySql 按名称进行的搜索比与索引(整数)进行比较。理论上它的作用(谷歌可以更好地解释它)是将文本转换为索引并验证它,而使用索引它只是访问它。我认为没有什么问题 - 事实上,我支持 - 将 id 列作为主键的想法。如果您担心重复,那么您可以在 site_name 列上设置唯一。

  1. 创建迁移以创建表

    php artisan make:migration settings_table
  2. 填写您的迁移代码

    <?php

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

    class SettingsTable extends Migration
    {
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
    Schema::create('settings', function (Blueprint $table) {
    //$table->increments('id'); This will come in hand, trust me
    $table->string('site_name',255)->unique();
    //If you really insist on having site_name as primary key, then use the line below
    // $table->string('site_name',255)->primary();
    $table->string('value',255);
    //$table->timestamps(); Do you need?
    });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
    Schema::dropIfExists('settings');
    }
    }
  3. 创建 Eloquent 模型

    php artisan make:model Setting
  4. 填写您的 Eloquent 模型

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    class Setting extends Model
    {
    protected $fillable = ['site_name','value'];
    //protected $table = ['settings'] Only if you really need it
    //Usually, if you take Laravel's approach, Models are singular version of the tables, that are in plural, but you can work it as you like
    }

关于mysql - 在 Mysql 中创 build 置表并在 laravel 中使用 eloquent 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51508804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com