简体   繁体   English

在 laravel 中运行 php 工匠迁移时,我们可以排除自定义服务提供商吗?

[英]Can we exclude a custom service provider when running php artisan migrate in laravel?

I have a custom service provider in which I am accessing a model in boot() .我有一个自定义服务提供商,我在其中访问 model 中的boot() But when I run php artisan migrate , it shows the below error:但是当我运行php artisan migrate时,它​​显示以下错误:

[Illuminate\Database\QueryException] SQLSTATE[42S02]: Base table or view not found: 1146 Table '********' doesn't exist

I found that if we add if ( app()->runningInConsole()) { inside boot() , it works successfully.我发现如果我们在boot()中添加if ( app()->runningInConsole()) { ,它就会成功。

This is the code we have used in the service provider:这是我们在服务提供者中使用的代码:

public function boot()
{
    $this->bindCurrentPartToNav();
}
private function bindCurrentPartToNav(): void
{
    $currentPartName = \App\Http\Helpers\Part::getPartName();

    view()->composer(
        'includes.partials.part',
        function ($view) use ($currentPartName) {
            $view->with('currentPartName', $currentPartName);
        }
    );
}

Helper file:帮助文件:

public static function getPartName(): ?string
{
    return PartModel::PartKey()->active()->pluck('name')->first();
}

Model: Model:

public function scopePartKey($query): Builder
{
    return $query->where('identifier', config('env.PART_KEY'));
}

Is there any way to remove that service provider from php artisan migrate so that we can remove runningInConsole() check in each refresh?有没有办法从php artisan migrate中删除该服务提供者,以便我们可以在每次刷新时删除runningInConsole()检查?

Thanks for your help in advance.提前感谢您的帮助。 在此处输入图像描述

As any environment configuration, in your case a general configuration, you should assign a default value fall back.与任何环境配置一样,在您的情况下是一般配置,您应该分配一个默认值回退。

public static function getSectionName(): ?string
{
    try {
        return SectionModel::sectionKey()->active()->pluck('name')->first();
    } catch (\Exception $e) {
        return null;
    }
}

This will simulate the case where the section model with that specific identification_key is missing in the database.这将模拟数据库中缺少特定identification_key密钥的 model 部分的情况。

This will also prevent any issues with the initial migration.这也将防止初始迁移出现任何问题。

But in the end, you tied a model with a view rendering code.但是最后,你用视图渲染代码绑定了一个 model。 You should find another solution to dissociate them.您应该找到另一种解决方案来分离它们。 For example, you can move the boot() code out of the model and link it to a middleware.例如,您可以将 boot() 代码移出 model 并将其链接到中间件。

You can also use Singleton pattern (since it's like a general unique config across the application)您还可以使用 Singleton 模式(因为它就像整个应用程序中的通用唯一配置)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM