该文章距离发布日期已经过了 1003 天 ,请注意信息甄别。


有时候项目中我们需要做一张只有键值的表,可以动态的设置字段,如果使用 laravel 内置的 model 去操作会不太方便,所以就有了下面这个模型。
可以快速使用get() set() 等方法快速读取和设置键的值。

  • getAll() 获取全部,一个键值对应的集合
  • exists() 判断某个键是否存在
  • get() 获取键的值,没有返回 null
  • set() 设置键值,可以单个或数组,不存在则创建
  • remove() 删除键记录

数据库迁移表

//2020_12_01_181940_create_sys_conf_table.php
<?php

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

class CreateSysConfTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('sys_conf', function (Blueprint $table) {
            $table->string('key')->unique()->primary();
            $table->json('value')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('sys_conf');
    }
}

模型代码

//SysConf.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\SysConf
 *
 * @property string $key
 * @property array|null $value
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|SysConf newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|SysConf newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|SysConf query()
 * @method static \Illuminate\Database\Eloquent\Builder|SysConf whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SysConf whereKey($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SysConf whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|SysConf whereValue($value)
 * @mixin \Eloquent
 */
class SysConf extends Model
{
    use HasFactory;

    protected $fillable = ['key', 'value'];

    protected $table = 'sys_conf';

    protected $casts = [
        'value' => 'array',
    ];

    /**
     * Get the ALL conf value.
     *
     * @param  string  $key
     * @return bool
     */
    public function getAll()
    {
        return self::all()->pluck('value', 'key');
    }
    /**
     * Determine if the given conf value exists.
     *
     * @param  string  $key
     * @return bool
     */
    public function exists($key)
    {
        return self::where('key', $key)->exists();
    }

    /**
     * Get the specified conf value.
     *
     * @param  string  $key
     * @param  mixed   $default
     * @return mixed
     */
    public function get($key, $default = null)
    {
        if ($conf = self::where('key', $key)->first()) {
            return $conf->value;
        }

        return $default;
    }

    /**
     * Set a given conf value.
     *
     * @param  array|string  $key
     * @param  mixed   $value
     * @return void
     */
    public function set($key, $value = null)
    {
        $keys = is_array($key) ? $key : [$key => $value];

        foreach ($keys as $key => $value) {
            self::updateOrCreate(['key' => $key], ['value' => $value]);
        }

        // @todo: return the conf
    }

    /**
     * Remove/delete the specified conf value.
     *
     * @param  string  $key
     * @return bool
     */
    public function remove($key)
    {
        return (bool) self::where('key', $key)->delete();
    }
}