laravel-learn-bbs/app/Models/Topic.php

76 lines
1.8 KiB
PHP
Raw Normal View History

2018-01-01 04:00:45 +00:00
<?php
namespace App\Models;
2018-06-10 10:04:03 +00:00
/**
* Class Topic
* @property int id
* @property string title
* @property int category_id
* @property int user_id
* @property int reply_count
* @property int view_count
* @property int last_reply_user_id
* @property string body
* @property string slug
* @property string excerpt
* @property string created_at
* @property string updated_at
* @package App\Models
*/
2018-01-01 04:00:45 +00:00
class Topic extends Model
{
2018-01-01 08:32:20 +00:00
protected $fillable = ['title', 'category_id', 'body', 'excerpt', 'slug'];
2018-01-01 06:51:46 +00:00
2018-01-31 15:00:57 +00:00
public function link($params = [])
2018-01-01 13:22:16 +00:00
{
return route('topics.show', array_merge([$this->id, $this->slug], $params));
}
2018-01-01 07:22:14 +00:00
public function scopeWithOrder($query, $order)
{
// 不同的排序,使用不同的数据读取逻辑
switch ($order) {
case 'recent':
$query = $this->recent();
break;
default:
$query = $this->recentReplied();
break;
}
// 预加载防止 N+1 问题
return $query->with('user', 'category');
}
public function scopeRecentReplied($query)
{
// 当话题有新回复时,我们将编写逻辑来更新话题模型的 reply_count 属性,
// 此时会自动触发框架对数据模型 updated_at 时间戳的更新
return $query->orderBy('updated_at', 'desc');
}
public function scopeRecent($query)
{
// 按照创建时间排序
return $query->orderBy('created_at', 'desc');
}
2018-01-15 15:24:11 +00:00
public function replies()
{
return $this->hasMany(Reply::class);
}
2018-01-01 06:51:46 +00:00
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
2018-01-01 04:00:45 +00:00
}