2017-02-21 56 views
0

我有一個類似下面的評論系統。用戶可以評論文章,圖片和帖子。一切正常。但除此之外,我想添加一個用戶可以評論網站本身的部分,就像一般評論一樣。我想將其與現有評論系統集成。但是,自然地,我沒有可以添加關係的網站本身的表格或模型。什麼是一個好的方法去?如何在laravel的現有評論系統中添加/集成一般網站評論?

表是這樣的:

articles 
    id - integer 
    title - string 
    body - text 

posts 
    id - integer 
    title - string 
    body - text 

images 
    id - integer 
    title - integer 
    path - text 

comments 
    id - integer 
    comment - text 
    commentable - integer 
    commentable_type - string 

和模式是這樣的:

class Post extends Model 
{ 
    public function comments() 
    { 
     return $this->morphMany(Comment::class, 'commentable'); 
    } 
} 

class Images extends Model 
{ 
    public function comments() 
    { 
     return $this->morphMany(Comment::class, 'commentable'); 
    } 
} 

class Article extends Model 
{ 
    public function comments() 
    { 
     return $this->morphMany(Comment::class, 'commentable'); 
    } 
} 

class Comment extends Model 
{ 
    public function commentable() 
    { 
     return $this->morphTo(); 
    } 
} 
+0

如果你有可能有一個'用戶'表,那麼可能是它的時間來添加評論關係到'用戶'模型?即成爲評論的一部分也只是想辦法...... –

回答

1

既然你只有一個網站,你可以設置你的變身字段可爲空和範圍添加到您的Comment模型,將只返回那些與您的網站相關的評論,如下所示:

public function scopeForWebsite($query) { 
    return $query->where(function($query) { 
     $query->whereNull('commentable')->whereNull('commentable_type'); 
    }); 
} 

,然後使用檢索您的網站評論:

Comment::forWebsite()->get()

在創建註釋只是不要將它連接到任何實體,它會被當作一個全球性的,通用的一個。

只要記住,你需要在你的遷移手動添加commentablecommentable_type領域(而不是假定$table->morphs('commentable')),它們標記爲可爲空和索引的字段。

+0

你是完全正確的。我絕對會使用它。但爲什麼「索引這些領域」呢?你是否說過(通用)加速表或其他原因? – Skeletor

+1

Laravel在調用'$ table-> morphs(...);'時自動索引變形字段,但如果要手動添加這些字段,則需要自行添加索引。如果你不這樣做,你會在使用預加載時遇到性能問題(例如'Article :: with('comments') - > all()') – Mariusz