forked from gothinkster/realworld-starter-kit
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Article.php
102 lines (87 loc) · 2.34 KB
/
Article.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace Conduit\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property integer id
* @property string slug
* @property string title
* @property string description
* @property string body
* @property integer user_id
* @property \Conduit\Models\User user
* @property \Illuminate\Database\Eloquent\Collection comments
* @property \Carbon\Carbon created_at
* @property \Carbon\Carbon update_at
*/
class Article extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'slug',
'title',
'description',
'body',
'user_id',
];
public function setSlugAttribute($value)
{
$index = 0;
$slug = $value;
while (self::newQuery()
->where('slug', $slug)
->where('id', '!=', $this->id)
->exists()) {
$slug = $value . '-' . ++$index;
}
return $this->attributes['slug'] = $slug;
}
/********************
* Relationships
********************/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Create favorites relationship with users
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function favorites()
{
return $this->belongsToMany(User::class, 'user_favorite');
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
/**
* Check if given user has favorited this article
*
* @param null $id
*
* @return bool
*/
public function isFavoritedByUser($id = null)
{
if (is_null($id)) {
return false;
}
if ($id instanceof self) {
$id = $id->id;
}
return $this->newBaseQueryBuilder()
->from('user_favorite')
->where('user_id', $id)
->where('article_id', $this->id)
->exists();
}
}