InsertController.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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' => '5'])
  24. ->andWhere(['nombre' => 'Nivel 5-B3'])
  25. ->one();
  26. foreach($municipios->each() as $municipio) {
  27. $this->stdout("Procesando {$municipio['nombre']}\n");
  28. $existe = NivelMunicipio::find()
  29. ->andWhere(['[[idMunicipio]]' => $municipio['id']])
  30. ->andWhere(['eliminado' => null])
  31. ->exists();
  32. if ($existe) {
  33. continue;
  34. }
  35. $nivelMunicipio = new NivelMunicipio();
  36. $nivelMunicipio->uuid();
  37. $nivelMunicipio->idMunicipio = $municipio['id'];
  38. $nivelMunicipio->idNivel = $nivel->id;
  39. $nivelMunicipio->creado = new Expression('now()');
  40. if (!$nivelMunicipio->save()) {
  41. $errores = Json::encode($nivelMunicipio->getFirstErrors());
  42. $this->stdout("Ocurrió un error con el municipio {$municipio['nombre']}: {$errores}\n");
  43. }
  44. }
  45. }
  46. }