Laravel计数量,其中键的值在多维数组中为真

时间:2016-06-14 10:55:53

标签: php arrays laravel

当dd出来时,我有一个看起来像这样的数组:)

array:2 [▼
  0 => Comment {#253 ▼
    #guarded: []
    #table: "comments"
    +timestamps: false
    #connection: null
    #primaryKey: "id"
    #perPage: 15
    +incrementing: true
    #attributes: array:7 [▶]
    #original: array:7 [▼
      "id" => "1"
      "on_projects" => "2"
      "from_user" => "19"
      "body" => "hi"
      "unread" => "1"
      "created_at" => "2016-06-13 23:54:39"
      "updated_at" => "0000-00-00 00:00:00"
    ]
    #relations: []
    #hidden: []
    #visible: []
    #appends: []
    #fillable: []
    #dates: []
    #dateFormat: null
    #casts: []
    #touches: []
    #observables: []
    #with: []
    #morphClass: null
    +exists: true
    +wasRecentlyCreated: false
  }
  1 => Comment {#269 ▶}
]

现在我的目标是计算未读密钥的真实位置。

这是我尝试过但似乎没有用的。

$unreads = $comments->where('unread', 1);
dd(count($unreads));

我收到此错误:

  

调用成员函数where()on array

任何人都可以帮助我吗?

非常感谢提前!

修改

$uid = Auth::user()->id;
$projects = User::find($uid)->projects;

//comments
if (!empty($projects)) {
  foreach ($projects as $project) {              
     $comments_collection[] = $project->comments;
  }
}

if (!empty($comments_collection)) {
     $comments = array_collapse($comments_collection);
     $unreads = collect($comments)->where('unread', 1)->count();
     dd($unreads);
}

这给了我0它应该给我2因为我有2条评论未读1

1 个答案:

答案 0 :(得分:3)

检索完数据后,您可以使用Illuminate \ Collection收集,过滤和计数。

collect($comments)->where('unread', 1)->count();

也就是说,如果您的目标是简单地计算数据而不对其执行任何其他操作,则可以使用Eloquent实现此目的,因为您可能已经使用了类似的查询来获取数据。

Comments::where('unread', 1)->count();

根据OP编辑进行修改。

$projects = Project::with(['comments'])
    ->where('user_id', Auth::id())
    ->get();

$count = $projects->sum(function ($project) {
    return $project->comments->where('unread', 1)->count();
});

dd($count);

想到了更多关于它的信息,因为你只想要一个计数(似乎),你可以为你的Project模型添加一个关系和一个访问器。

public function commentsCountUnread() {
  return $this->hasOne(Comment::class)
    ->selectRaw('project_id, count(*) as aggregate')
    ->where('unread', 1)
    ->groupBy('project_id');
}

public function getCommentsCountUnreadAttribute()
{
  if (! $this->relationLoaded('commentsCountUnread')) {
    $this->load('commentsCountUnread');
  }

  $related = $this->getRelation('commentsCountUnread');

  return ($related) ? (int) $related->aggregate : 0;
}

然后你可以做类似

的事情
$posts = Project::with('commentsCountUnread')->get();

$count = $projects->sum(function($project) {
  return $project->commentsCountUnread;
});

dd($count);