在mysql中创建设置表并在laravel中使用elokent获取

new9mtju  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(334)

我想创建一个包含两列(设置,值)的设置表,设置将包含类似site\的内容,而值将是“facebook”或“youtube”之类的内容。这将持有网站名称,标志网址等。我将如何创建这一点,最重要的是,我将如何获取没有一个id字段与拉威尔雄辩的信息。

7kqas0il

7kqas0il1#

第一件事。
你的table需要一张table primary key . 那会是一个好主意吗 varchar 根据你的例子?mysql的按名称搜索要比比较索引(整数)慢得多。它在理论上的作用(谷歌可以更好地解释)是将文本转换成一个索引并验证它,而索引只是访问它。事实上,我支持拥有一个 id 列作为主键。如果您担心重复,那么可以在列上设置unique site_name .
创建迁移以创建表

php artisan make:migration settings_table

填写迁移代码

<?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');
    }
}

创造一个有说服力的模型

php artisan make:model Setting

充满你雄辩的模型

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
}

相关问题