BlogPosts.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace app\models;
  3. use Yii;
  4. use yii\behaviors\SluggableBehavior;
  5. use yii\web\UploadedFile;
  6. /**
  7. */
  8. class BlogPosts extends \yii\db\ActiveRecord
  9. {
  10. public $imageFile;
  11. public static function tableName()
  12. {
  13. return 'blogposts';
  14. }
  15. public function behaviors()
  16. {
  17. return [
  18. [
  19. 'class' => SluggableBehavior::className(),
  20. 'attribute' => 'title',
  21. 'slugAttribute' => 'slug',
  22. ]
  23. ];
  24. }
  25. public function rules()
  26. {
  27. return [
  28. [['title', 'text', 'cat_id','description','key_words','h1','short_text'], 'required'],
  29. [['text','short_text','slug','text_ru','short_text_ru'], 'string'],
  30. [['cat_id', 'created_at'], 'integer'],
  31. [['title', 'picture','description','key_words','h1','title_ru','description_ru','key_words_ru','h1_ru'], 'string', 'max' => 255],
  32. [['title','slug'], 'unique'],
  33. [['imageFile'],'file','extensions' => 'png, jpg, gif']
  34. ];
  35. }
  36. public function attributeLabels()
  37. {
  38. return [
  39. 'id' => Yii::t('app', 'ID'),
  40. 'title' => Yii::t('app', 'Title'),
  41. 'description' => Yii::t('app', 'Description'),
  42. 'key_words' => Yii::t('app', 'Key words'),
  43. 'text' => Yii::t('app', 'Text'),
  44. 'imageFile' => Yii::t('app', 'Picture'),
  45. 'cat_id' => Yii::t('app', 'Cat ID'),
  46. 'h1' => Yii::t('app', 'H1'),
  47. 'short_text' => Yii::t('app','Short text'),
  48. 'title_ru' => Yii::t('app', 'Title ru'),
  49. 'text_ru' => Yii::t('app', 'Text ru'),
  50. 'cat_id_ru' => Yii::t('app', 'Cat ID ru'),
  51. 'h1_ru' => Yii::t('app', 'H1 ru'),
  52. 'short_text_ru' => Yii::t('app','Short text ru'),
  53. 'slug' => Yii::t('app','Slug'),
  54. ];
  55. }
  56. public function getPicture()
  57. {
  58. return $this->picture ? '/'. $this->picture : false ;
  59. }
  60. public function getCategory()
  61. {
  62. return $this->hasOne(Categoriesblog::className(),['id' => 'cat_id']);
  63. }
  64. public function getShort($length = 600){
  65. return mb_strlen($this->text, 'utf-8') > $length ? mb_substr($this->text, 0, $length, 'utf-8') . '...' : $this->text;
  66. }
  67. public function getLogo()
  68. {
  69. return $this->picture ? '/'. $this->picture : false ;
  70. }
  71. public function upload(){
  72. if(false != ($file = UploadedFile::getInstance($this, 'picture'))){
  73. $filename = time() . $file->baseName . '.' . $file->extension;
  74. $path = 'uploads/posts';
  75. if($file->saveAs($path . DIRECTORY_SEPARATOR . $filename)){
  76. $this->picture = $filename;
  77. return $this->save();
  78. }
  79. }
  80. return $this->save();
  81. }
  82. }