Area.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace common\modules\area\models;
  3. use Yii;
  4. /**
  5. * This is the model class for table "{{%area}}".
  6. *
  7. * @property integer $area_id
  8. * @property string $title
  9. * @property string $slug
  10. * @property string $description
  11. * @property string $blocks
  12. */
  13. class Area extends \yii\db\ActiveRecord
  14. {
  15. /**
  16. * @inheritdoc
  17. */
  18. public static function tableName()
  19. {
  20. return '{{%area}}';
  21. }
  22. /**
  23. * @inheritdoc
  24. */
  25. public function rules()
  26. {
  27. return [
  28. [['title', 'slug', 'description'], 'required'],
  29. [['title', 'slug', 'description'], 'string'],
  30. ["blocks", "safe"]
  31. ];
  32. }
  33. /**
  34. * @inheritdoc
  35. */
  36. public function attributeLabels()
  37. {
  38. return [
  39. 'area_id' => 'ID',
  40. 'title' => '区域名',
  41. 'slug' => '标识',
  42. 'description' => '区域说明',
  43. 'blocks' => '区块',
  44. ];
  45. }
  46. public function beforeSave($insert)
  47. {
  48. if(parent::beforeSave($insert) == false) {
  49. return false;
  50. }
  51. $this->blocks = serialize($this->blocks);
  52. return true;
  53. }
  54. public function afterFind()
  55. {
  56. parent::afterFind();
  57. $this->blocks = unserialize($this->blocks);
  58. }
  59. public function getBlocks() {
  60. if(!empty($this->blocks)) {
  61. $query = Block::find()->where(['block_id' => $this->blocks])->orderBy([new \yii\db\Expression('FIELD (block_id, ' . implode(', ', $this->blocks) . ')')]);
  62. return $query->all();
  63. }
  64. return [];
  65. }
  66. public static function findByIdOrSlug($id)
  67. {
  68. if (intval($id) == 0) {
  69. $condition = ["slug" => $id];
  70. } else {
  71. $condition = [
  72. $id
  73. ];
  74. }
  75. return static::findOne($condition);
  76. }
  77. }