Book.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. namespace common\modules\book\models;
  3. use common\behaviors\CommentBehavior;
  4. use common\helpers\Tree;
  5. use common\models\Comment;
  6. use common\modules\attachment\behaviors\UploadBehavior;
  7. use Yii;
  8. use yii\behaviors\TimestampBehavior;
  9. /**
  10. * This is the model class for table "{{%book}}".
  11. *
  12. * @property integer $id
  13. * @property string $book_name
  14. * @property string $book_cover
  15. * @property string $book_link
  16. * @property integer $book_author
  17. * @property string $book_description
  18. * @property integer $view
  19. * @property integer $created_at
  20. * @property integer $updated_at
  21. * @property BookChapter $firstChapters
  22. * @property BookChapter[] $chapters
  23. */
  24. class Book extends \yii\db\ActiveRecord
  25. {
  26. /**
  27. * @inheritdoc
  28. */
  29. public static function tableName()
  30. {
  31. return '{{%book}}';
  32. }
  33. /**
  34. * @inheritdoc
  35. */
  36. public function rules()
  37. {
  38. return [
  39. [['book_author'], 'integer'],
  40. [['book_name'], 'string', 'max' => 50],
  41. [['book_cover', 'book_link'], 'string', 'max' => 255],
  42. [['book_description'], 'string', 'max' => 1000],
  43. ];
  44. }
  45. /**
  46. * @inheritdoc
  47. */
  48. public function attributeLabels()
  49. {
  50. return [
  51. 'id' => 'ID',
  52. 'book_name' => '书名',
  53. 'book_cover' => '书封面',
  54. 'book_author' => '作者',
  55. 'book_description' => '书简介',
  56. 'book_link' => '书外链',
  57. 'created_at' => '创建时间',
  58. 'updated_at' => '更新时间',
  59. ];
  60. }
  61. public function behaviors()
  62. {
  63. return [
  64. TimestampBehavior::className(),
  65. [
  66. 'class' => UploadBehavior::className(),
  67. 'attribute' => 'book_cover'
  68. ],
  69. CommentBehavior::className()
  70. ];
  71. }
  72. public function afterDelete()
  73. {
  74. parent::afterDelete();
  75. foreach ($this->chapters as $chapter) {
  76. $chapter->delete();
  77. }
  78. }
  79. public function getFirstChapter()
  80. {
  81. return $this->hasOne(BookChapter::className(), ['book_id' => 'id'])->orderBy(['sort' => SORT_ASC]);
  82. }
  83. public function getChapters()
  84. {
  85. return $this->hasMany(BookChapter::className(), ['book_id' => 'id'])->orderBy(['sort' => SORT_ASC]);
  86. }
  87. public function addView()
  88. {
  89. return $this->updateCounters(['view' => 1]);
  90. }
  91. /**
  92. * 获取所有评论数
  93. */
  94. public function getAllCommentTotal()
  95. {
  96. $chapters = $this->chapters;
  97. $chapterIds = [];
  98. $total = 0;
  99. foreach ($chapters as $chapter) {
  100. $total += $chapter->getCommentTotal();
  101. }
  102. return $total;
  103. }
  104. }