socoladaica / laravel-table-prefix

允许您在标准的 Laravel 模型中使用表前缀

1.2.0 2023-02-08 14:10 UTC

This package is auto-updated.

Last update: 2024-09-03 04:51:17 UTC


README

Latest Version on Packagist Build Status GitHub Tests Action Status Quality Score Total Downloads

允许您在标准的 Laravel 模型中使用表前缀。

灵感来源于[提案] 带前缀的 Eloquent 模型

安装

您可以通过 composer 安装此包

composer require socoladaica/laravel-table-prefix

用法

Post 模型中使用它将类似于这样

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Socoladaica\LaravelTablePrefix\HasTablePrefix;

class Post extends Model
{
    use HasTablePrefix;

    protected $prefix = 'blog_';

}

CategoryPost 模型中使用它将类似于这样

<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;
use Socoladaica\LaravelTablePrefix\HasTablePrefix;

class CategoryPost extends Pivot
{
    use HasTablePrefix;

    protected $prefix = 'blog_';

}

然而,如果有人使用这种方法并且有许多需要更新的带有前缀的模型,这可能会很麻烦。我们可以通过创建另一个特质(这个特质理论上将存在于用户代码中,而不是核心代码)来做得更好,比如说 BlogPrefix

<?php

namespace App;

use Socoladaica\LaravelTablePrefix\HasTablePrefix;

trait BlogPrefix
{
    use HasTablePrefix;

    /**
     * The table prefix associated with the model.
     * 
     * @var string
     */
    protected $prefix = 'blog_';

}

最终的模型可能看起来像这样

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use BlogPrefix;

}

最终的交叉模型可能看起来像这样

<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;
use Socoladaica\LaravelTablePrefix\HasTablePrefix;

class CategoryPost extends Pivot
{
    use BlogPrefix;

}

之后,您可以在迁移中使用它,如下所示

class CreateSocolaCmsBlogDatabase extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        Schema::create(Post::getTableName(), function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });

        Schema::create(Category::getTableName(), function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }

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

测试

composer test

变更日志

请参阅 CHANGELOG 以获取有关最近更改的更多信息。

贡献

请参阅 CONTRIBUTING 以获取详细信息。

安全

如果您发现任何安全相关的问题,请通过电子邮件 Socoladaica@gmail.com 而不是使用问题跟踪器。

鸣谢

许可证

MIT 许可证 (MIT)。请参阅 许可证文件 以获取更多信息。