【问题标题】:Append Laravel model namespace as table prefix追加 Laravel 模型命名空间作为表前缀
【发布时间】:2018-05-29 19:35:15
【问题描述】:

我正在开发一个包含多个“应用程序”的 Laravel 5.5 项目:文章、笔记、照片等。

每个应用程序都应该有自己的目录/命名空间,包含其模型:

app/
    Blog/
        Article.php
        Category.php
    Notes/
        Note.php
        Category.php
    ...

当我运行此命令php artisan make:model --migration Blog/Category 时,它成功创建了app/Blog/Category.php 模型和App\Blog 命名空间,但关联的迁移创建了一个名为category 的表,而不是blog_category。这是有问题的,因为我还需要创建app/Notes/Category.php

前缀category 表有什么技巧吗?如果我手动更改它们的名称,Laravel 会解析这些表,还是必须在每个模型中添加 $table 属性?

Model 命名空间和表名没有前缀相关,遵循 Laravel 逻辑,这不是很奇怪吗?

【问题讨论】:

  • 如果这样更容易,您实际上可以创建自己的迁移,例如php artisan make:migration create_blog_category_table。另外请注意,插入到blog_categorynote_category 中的记录除了父模型之外会有什么区别吗?

标签: php laravel model laravel-artisan


【解决方案1】:

有两种选择来解决它:

  • 使用将创建 blog_articles 表的 BlogArticle 制作模型
  • 或将$table="your table name" 添加到每个模型

【讨论】:

    【解决方案2】:

    这个特性可以帮助你

    use Illuminate\Support\Str;
    
    trait TableNameResolver
    {
        public $base_namespace=__NAMESPACE__;
    
        public function getTable()
        {
            if (! isset($this->table)) {
               $this->setTable(str_replace(
                    '\\', '', Str::snake(Str::plural(trim(str_after(get_class($this),trim($this->base_namespace,'\\')),'\\')))
                ));
            }
            return $this->table;
        }
    }
    

    【讨论】:

    • 一直在寻找这个。我做了一些更改以使其更加突出。谢谢老兄。
    【解决方案3】:

    按照 the_hasanov 的答案:

    我做了一些改动,效果很好。

    namespace App\Traits;
    
    use Illuminate\Support\Str;
    
    trait ModelTrait
    {
    
        /**
         * Scopped Variables
         */
        protected $table_prefix              =  "prefix_";
    
        /**
         * Appends prefix to table name
         * 
         * @return $table
         */
        public function getTable() {
    
            $model                           =  explode("\\", get_class($this));
            $model                           =  Str::lower(array_pop($model));
    
            if (!isset($this->table)) $this->setTable(Str::plural($this->table_prefix . $model));
    
            return $this->table;
    
        }
    
    }
    

    添加这样的特征并在模型中像这样使用它:

    class Model {
        use ModelTrait;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      相关资源
      最近更新 更多