简体   繁体   English

如何在 laravel 迁移中添加异常?

[英]how to add exception in laravel migration?

I'm doing a migration and I want the execution of "artisan migrate" to stop until a field does not have the value 'CONTACT_INFO' inside.我正在进行迁移,我希望停止执行“工匠迁移”,直到字段内部没有值“CONTACT_INFO”。
What I want to do is an exception when I detect that this value is not there.当我检测到该值不存在时,我想要做的是一个异常。

 public function up()
    {
        $emailConfiguration = EConfig::where('clave','CONTACTO_NAME')->get()->first();
        $eConfig = EConfig::find($emailConfiguration->pages_id);
        $Languages = Language::all();

        foreach ($Languages as $key => $lang) {
            $exists = !is_null($eConfig->pages_id);
            if ($exists) {
                $value = $eConfig->detail()->where('language_id', $lang->languages_id)->first()->pages_valor;
                if (strpos($value,'CONTACTO_INFO') == false) {
                    InvalidOrderException::reportable(function (InvalidOrderException $e) {
                        echo 'error';
                    });
                }
            }
        }
        
        
    }

If I'm understanding your question correctly, you want to stop the migrations if a certain condition is not satisfied.如果我正确理解您的问题,如果不满足某个条件,您希望停止迁移。

To do so, you need to throw the exception you want, for instance, with your code:为此,您需要抛出您想要的异常,例如,使用您的代码:

public function up()
{
        //... 

        foreach ($Languages as $key => $lang) {
            $exists = !is_null($eConfig->pages_id);
            
            if ($exists) {
                // ...
                if (strpos($value,'CONTACTO_INFO') == false) {
                    throw new \RuntimeException('Migration stopped due to invalid data');
                }
            }
        }    
}

However you may want to wrap it in a transaction to avoid any undesired behaviors但是,您可能希望将其包装在事务中以避免任何不良行为

use Illuminate\Support\Facades\DB;

public function up()
{
  DB::transaction(function(){
          //... 

          foreach ($Languages as $key => $lang) {
              $exists = !is_null($eConfig->pages_id);
            
              if ($exists) {
                  // ...
                  if (strpos($value,'CONTACTO_INFO') == false) {
                      throw new \RuntimeException('Migration stopped due to invalid data');
                  }
              }
          }    
  }
});

If you want to customize your exception, you can create your own with php artisan make:exception MyMigrationCustomException如果要自定义异常,可以使用php artisan make:exception MyMigrationCustomException创建自己的异常

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

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