InsertController.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace app\commands;
  3. use app\models\Nivel;
  4. use app\models\NivelMunicipio;
  5. use yii\console\Controller;
  6. use yii\db\Expression;
  7. use yii\db\Query;
  8. use yii\helpers\Json;
  9. class InsertController extends Controller {
  10. public function actionNivelMunicipio() {
  11. $municipios = (new Query())
  12. ->select([
  13. '{{Municipio}}.id as id',
  14. '{{Municipio}}.nombre as nombre'
  15. ])
  16. ->from('Municipio')
  17. ->innerJoin('Estado', '{{Municipio}}.[[idEstado]] = {{Estado}}.id')
  18. ->andWhere(['{{Municipio}}.eliminado' => null])
  19. ->andWhere(['{{Estado}}.eliminado' => null])
  20. ->andWhere(['{{Estado}}.nombre' => 'TAMAULIPAS']);
  21. $nivel = Nivel::find()
  22. ->andWhere(['eliminado' => null])
  23. ->andWhere(['clave' => '4-A'])
  24. ->one();
  25. foreach($municipios->each() as $municipio) {
  26. $this->stdout("Procesando {$municipio['nombre']}\n");
  27. $existe = NivelMunicipio::find()
  28. ->andWhere(['[[idMunicipio]]' => $municipio['id']])
  29. ->andWhere(['eliminado' => null])
  30. ->exists();
  31. if ($existe) {
  32. continue;
  33. }
  34. $nivelMunicipio = new NivelMunicipio();
  35. $nivelMunicipio->uuid();
  36. $nivelMunicipio->idMunicipio = $municipio['id'];
  37. $nivelMunicipio->idNivel = $nivel->id;
  38. $nivelMunicipio->creado = new Expression('now()');
  39. if (!$nivelMunicipio->save()) {
  40. $errores = Json::encode($nivelMunicipio->getFirstErrors());
  41. $this->stdout("Ocurrió un error con el municipio {$municipio['nombre']}: {$errores}\n");
  42. }
  43. }
  44. }
  45. }