AppServiceProvider 内提前注册DB Query扩展自定义方法的方式;
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Query\Builder AS queryBuilder;
use Illuminate\Database\Eloquent\Builder AS eloquentBuilder;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Cache;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->_dbQueryBuilderMacro();
}
private function _dbQueryBuilderMacro()
{
queryBuilder::macro('toColumn', function(){
$_tableName = $this->from;
if( stripos($_tableName, 'as') !== false ){
$_tableName = trim(explode('as', $_tableName)[0]);
}
$_connectionName = $this->connection->getConfig('name');
$_cacheName = sprintf('DB:TABLE_COLUMN:%s:%s',$_connectionName, $_tableName);
if (Cache::has($_cacheName)) {
$columns = json_decode(Cache::get($_cacheName),true);
}else{
$columns = Schema::connection($_connectionName)
->getColumnListing($_tableName);
if (!empty($columns)){
Cache::set($_cacheName,json_encode($columns));
}
}
return $columns;
});
eloquentBuilder::macro('toColumn', function(){
return $this->getQuery()->toColumn();
});
}
}
使用方法也很简单:
$_mUser = new \App\Models\Users;
dd($_mUser->toColumn());
|