laravel 批量设置 fiilable的办法 
                                                    
                        
                    
                    
  
                    
                    家人们,之前用hyperf,在用命令创建model的时候,会自动填充文件的fillable,
但是laravel要自己写,字段很多,模型文件也很多,欲哭无泪啊
咋就是说我能不能通过动态方式去设置呢?
fillable 对model 内部是可见的,那我写个基类修改fillable不就好了
<?php
namespace App\Models;
use Illuminate\Support\Facades\Schema;
class Model extends \Illuminate\Database\Eloquent\Model
{
    public function __construct()
    {
        parent::__construct();
        // 设置fillable
        $this->fillable = $this->getTableColumns($this->getTable());
    }
    protected function getTableColumns($tableName)
    {
        Schema::connection()->getColumnListing($tableName);
    }
}咋一看好像没问题,但是因为是基类,一步小心sql就执行的巨多

啊啊啊,全是查表结构对的
于是进行优化,我们可以把表名和字段映射成一个map,做成静态的,直接读取就好了
<?php
namespace App\Models;
use Illuminate\Support\Facades\Schema;
class Model extends \Illuminate\Database\Eloquent\Model
{
    protected static $tableColumnsMap;
    public function __construct()
    {
        parent::__construct();
        // 设置fillable
        $this->fillable = $this->getTableColumns($this->getTable());
    }
    protected function getTableColumns($tableName)
    {
        if (isset(self::$tableColumnsMap[$this->getTable()])) return self::$tableColumnsMap[$this->getTable()];
        self::$tableColumnsMap[$this->getTable()] =  Schema::connection()->getColumnListing($tableName);
        return self::$tableColumnsMap[$this->getTable()];
    }
}啊啊啊,这下舒服了,舒服了!
本作品采用《CC 协议》,转载必须注明作者和本文链接
 
           晏南风 的个人博客
 晏南风 的个人博客
         
             
             
                     
                     
             
         
             
         
        
 
             
             
             
             
             
             
             
         
             
             
             
             
            
 
             
             
             
            
 
             
           
           关于 LearnKu
                关于 LearnKu
               
                     
                     
                     粤公网安备 44030502004330号
 粤公网安备 44030502004330号 
 
推荐文章: