ALTER TABLE migration_demo CHANGE type demo_type INT DEFAULT 0 NOT NULL
ALTER TABLE migration_demo CHANGE type type BIGINT DEFAULT 0 NOT NULL
//无效方式2
Schema::table('migration_demo', function (Blueprint $table) {
$table->bigInteger('type')->default('0')->change()->renameColumn('type', 'demo_type');
});
执行语句 ,rename并没有生效
ALTER TABLE migration_demo CHANGE type type BIGINT DEFAULT 0 NOT NULL
同一字段执行多种变更,正确的方式
Schema::table('demo', function (Blueprint $table) {
$table->renameColumn('name', 'demo_name');
});
Schema::table('demo', function (Blueprint $table) {
$table->string('demo_name', 255)->default('')->change();
});
执行语句结果
ALTER TABLE demo CHANGE demo_name demo_name VARCHAR(255) DEFAULT '' NOT NULL COLLATE utf8mb4_unicode_ci
ALTER TABLE demo CHANGE name demo_name VARCHAR(20) DEFAULT '' NOT NULL
Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables;
/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
//此处判断是否开启缓存配置,开启缓存配置直接返回缓存中的配置
//因此开启缓存配置后,env()函数会失效
if ($app->configurationIsCached()) {
return;
}
$this->checkForSpecificEnvironmentFile($app);
//此处加载.env中的文件
try {
(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
} catch (InvalidPathException $e) {
//
}
}
/**
* Gets the value of an environment variable.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
function env($key, $default = null)
{
$value = getenv($key);
if ($value === false) {
return value($default);
}
switch (strtolower($value)) {
case 'true':
case '(true)':
return true;
case 'false':
case '(false)':
return false;
case 'empty':
case '(empty)':
return '';
case 'null':
case '(null)':
return;
}
if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) {
return substr($value, 1, -1);
}
return $value;
}
/**
* Get / set the specified configuration value.
*
* If an array is passed as the key, we will assume you want to set an array of values.
*
* @param array|string $key
* @param mixed $default
* @return mixed|\Illuminate\Config\Repository
*/
function config($key = null, $default = null)
{
if (is_null($key)) {
return app('config');
}
if (is_array($key)) {
return app('config')->set($key);
}
return app('config')->get($key, $default);
}
//app('config) 生成的是 Illuminate\Config\Repository 实例
/**
* Get a generator for the given query.
*
* @return \Generator
*/
public function cursor()
{
foreach ($this->applyScopes()->query->cursor() as $record) {
yield $this->model->newFromBuilder($record);
}
}
chunk() 分块处理 适用于小数据量快速处理
Flight::chunk(200, function ($flights) {
foreach ($flights as $flight) {
//
}
});
内部实现 do while 循环 执行的分页查询sql 耗时和消耗内存取决分块数量,分块数量越大消耗内存和耗时相应减少
select * from `flights` order by `flights`.`id` asc limit 200 offset 0
select * from `flights` order by `flights`.`id` asc limit 200 offset 200
select * from `flights` order by `flights`.`id` asc limit 200 offset 400
/*
|--------------------------------------------------------------------------
| Horizon Redis Connection
|--------------------------------------------------------------------------
|
| This is the name of the Redis connection where Horizon will store the
| meta information required for it to function. It includes the list
| of supervisors, failed jobs, job metrics, and other information.
|
*/
'use' => 'payhandle',
/*
|--------------------------------------------------------------------------
| Horizon Redis Prefix
|--------------------------------------------------------------------------
|
| This prefix will be used when storing all Horizon data in Redis. You
| may modify the prefix when you are running multiple installations
| of Horizon on the same server so that they don't have problems.
|
*/
'prefix' => env('HORIZON_PREFIX', 'horizon:'),
/*
|--------------------------------------------------------------------------
| Horizon Route Middleware
|--------------------------------------------------------------------------
|
| These middleware will get attached onto each Horizon route, giving you
| the chance to add your own middleware to this list or change any of
| the existing middleware. Or, you can simply stick with this list.
|
*/
'middleware' => ['web'],
/*
|--------------------------------------------------------------------------
| Queue Wait Time Thresholds
|--------------------------------------------------------------------------
|
| This option allows you to configure when the LongWaitDetected event
| will be fired. Every connection / queue combination may have its
| own, unique threshold (in seconds) before this event is fired.
|
*/
'waits' => [
'redis:default' => 60,
],
/*
|--------------------------------------------------------------------------
| Job Trimming Times
|--------------------------------------------------------------------------
|
| Here you can configure for how long (in minutes) you desire Horizon to
| persist the recent and failed jobs. Typically, recent jobs are kept
| for one hour while all failed jobs are stored for an entire week.
|
*/
'trim' => [
'recent' => 60,
'failed' => 10080,
],
/*
|--------------------------------------------------------------------------
| Fast Termination
|--------------------------------------------------------------------------
|
| When this option is enabled, Horizon's "terminate" command will not
| wait on all of the workers to terminate unless the --wait option
| is provided. Fast termination can shorten deployment delay by
| allowing a new instance of Horizon to start while the last
| instance will continue to terminate each of its workers.
|
*/
'fast_termination' => false,
/*
|--------------------------------------------------------------------------
| Queue Worker Configuration
|--------------------------------------------------------------------------
|
| Here you may define the queue worker settings used by your application
| in all environments. These supervisors and settings handle all your
| queued jobs and will be provisioned by Horizon during deployment.
|
*/
'environments' => [
'production' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'simple',
'processes' => 10,
'tries' => 3,
],
],
'local' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'simple',
'processes' => 3,
'tries' => 3,
],
],
],
<?php
namespace App\Providers;
use DateInterval;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Bridge\PersonalAccessGrant;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*/
public function boot()
{
$this->registerPolicies();
//设置个人token失效时间为7天
$authorizarionServer = app()->make(\League\OAuth2\Server\AuthorizationServer::class);
$authorizarionServer->enableGrantType(
new PersonalAccessGrant(),
new DateInterval('PT7D')
);
}
}
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
}
2.存储到磁盘
public function storeExcel()
{
// Store on default disk
Excel::store(new InvoicesExport(2018), 'invoices.xlsx');
// Store on a different disk (e.g. s3)
Excel::store(new InvoicesExport(2018), 'invoices.xlsx', 's3');
// Store on a different disk with a defined writer type.
Excel::store(new InvoicesExport(2018), 'invoices.xlsx', 's3', Excel::XLSX);
}
参数1为导出类
参数2为文件名
参数3为laravel存储的磁盘
参数4为导出格式 详情看配置文件
从集合导出
<?php
namespace App\Exports;
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
namespace App\Exports;
use App\Invoice;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
class InvoicesExport implements FromQuery
{
use Exportable;
public function query()
{
return Invoice::query();
}
}
namespace App\Exports;
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\Queue\ShouldQueue;
class UsersExport implements FromCollection, ShouldQueue
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return User::all();
}
}
队列直接下载导出 控制器代码
public function export(Request $request, Excel $excel)
{
return $excel->download(new UsersExport(), 'users.xlsx');
}
队列导出存储到磁盘
public function store(Request $request)
{
ini_set('memory_limit', '1024M');
$result = Excel::store(new UsersExport(), 'users_store'.date('YmdHis').'.xlsx', 'public');
}
数据量大时,有时会超出内存限制需要设置内存,后来没复现,没找到原因
从 collection导出的方式,成功后没有发现导出excel文件,后来没复现,没有找到原因
设置表头
class InvoicesExport implements WithHeadings
{
public function headings(): array
{
return [
'对应ExcelA列',
'对应ExcelB列',
...
];
}
}
namespace App\Exports;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
class InvoicesExport implements ShouldAutoSize
{
...
}
自定义宽度
namespace App\Exports;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
class InvoicesExport implements WithColumnWidths
{
public function columnWidths(): array
{
//A B 是列的标识头
return [
'A' => 55,
'B' => 45,
];
}
}
常用配置修改
/*
|--------------------------------------------------------------------------
Heading Row Formatter
|--------------------------------------------------------------------------
|
| Configure the heading row formatter.
| Available options: none|slug|custom
|
*/
'heading_row' => [
'formatter' => 'none',//不格式化,这样可以导入中文标题头excel
],
/*
|--------------------------------------------------------------------------
| Transaction Handler
|--------------------------------------------------------------------------
|
| By default the import is wrapped in a transaction. This is useful
| for when an import may fail and you want to retry it. With the
| transactions, the previous import gets rolled-back.
|
| You can disable the transaction handler by setting this to null.
| Or you can choose a custom made transaction handler here.
|
| Supported handlers: null|db
|
*/
'transactions' => [
'handler' => 'null', //取消事物,不回滚,成功导入的数据不会被回滚
],