2014-01-10 22 views
2

我有一個使用軟刪除的模型Comments:它與我的Post模型有one-to-many關係。count()返回laravel中的軟刪除項目

我的網站將有一個原生的移動應用程序與它關聯,當我發送有關某個帖子的信息時,我需要向它發送一條評論的計數,並且由於某種原因,它將使用軟刪除的項目返回計數。

我已經得到了郵政陣列的同時發送在我的崗位模型中使用

protected $appends = array('score','commentcount', 'ups', 'downs'); 

public function getCommentcountAttribute() 
{  
    return DB::table('comments') 
     ->where('post_id',$this->id) 
     ->where('deleted_at','=',NULL) 
     ->count();  
} 

的評論數。我也試着

public function getCommentcountAttribute() 
{ 
    return $this->comments()->count(); 
} 

public function getCommentcountAttribute() 
{ 
    return $this->comments()->whereNull('deleted_at')->count(); 
    // also: return $this->comments()->where('deleted_at',NULL)->count(); 
} 

也確定我已經嘗試添加->whereNUll('deleted_at')到兩個->hasMany('Comment')->belongsTo('Post')沒有運氣的關係時。

我檢查了數據庫,並跑了我期待流利和雄辯是發電是

SELECT * FROM `comments` WHERE post_id=31 and deleted_at=null 

(31是我使用測試後)的SQL。沒有任何工作。讓我知道,如果你們需要看到更多的具體功能,我寧願不發佈我的整個模型。

回答

2

我能夠使它與->whereRaw('deleted_at = ?',array(NULL))一起工作。儘管這對我來說似乎很不好。我很樂意接受更好的答案。

1

您必須在模型中啓用軟刪除。

class Comment extends Eloquent { 

    protected $softDelete = true; 

} 

就是這樣。

而你並不需要包括以下where子句在查詢:只在模型

return \App\Comments::count(); 

軟刪除的作品,而不是查詢:

return DB::table('comments') 
     ->where('post_id',$this->id) 
     //->where('deleted_at','=',NULL) // no needed, Laravel by default will include this condition 
     ->count(); 


public function getCommentcountAttribute() 
{ 
    // remove ->whereNull('deleted_at') 
    return $this->comments()->count(); 
} 
+0

應該包括我已經做到了。除了當我使用' - > toArray()'和'count()'時,軟刪除工作無處不在 – MrJellyhands

1

更改您的代碼

class Comment extends Eloquent 
{ 
    protected $softDelete = true; 

}