php - count() 在 laravel 中返​​回软删除项

标签 php laravel eloquent fluent soft-delete

我有一个使用软删除的模型 Comments:它与我的 Post 模型有一个一对多 关系。

我的网站将有一个与之相关联的 native 移动应用程序,当我发送有关帖子的信息时,我需要向它发送评论计数,并且由于某种原因它返回带有软删除项目的计数。

我已经让 Post 数组正常工作并使用

发送评论计数
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') 没有运气。

我已经检查了数据库并运行了我期望 Fluent and Eloquent 生成的 SQL

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

(31 是我用来测试的帖子)。什么都不起作用。让我知道你们是否需要查看更多特定功能,因为我不想发布我的整个模型。

最佳答案

我能够让它与 ->whereRaw('deleted_at = ?',array(NULL)) 一起工作。不过,这对我来说似乎很老套。我很乐意接受更好的答案。

关于php - count() 在 laravel 中返​​回软删除项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21054567/

相关文章:

php - 如何让 PHPUnit 打印失败测试用例的完整输入?

javascript - WordPress插件功能,只有一个可以用吗?

php - 被拒绝 Apache2

php - 图片链接不适用于 codeigniter

laravel - 如何在 2 个 Eloquent 模型之间共享功能

在 foreach 循环中使用 Intro.js 的 php 问题

php - 如何合并两个 Eloquent 集合?

php - 相关数据的查询构建器结构

php - 使用 DB::raw 和 Eloquent 使用相同查询的不同结果

php - Laravel 基于多列数据值的唯一性验证