【问题标题】:Creating a settings table in Mysql and fetching with eloquent in laravel在 Mysql 中创建设置表并在 laravel 中使用 eloquent 获取
【发布时间】:2018-07-24 23:12:13
【问题描述】:

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

【问题讨论】:

    标签: mysql eloquent laravel-5.6


    【解决方案1】:

    首先要做的事情。

    您的表需要primary key。根据您的示例,这将是一个varchar 字段吗? MySql 按名称搜索WAY SLOWER 比将 an 与索引(整数)进行比较。它在理论上所做的(谷歌可以更好地解释它)在某种程度上将文本转换为索引并验证它,而使用索引它只是访问它。我认为没有错 - 事实上,我支持 - 将 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
      }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      相关资源
      最近更新 更多