[英]How in laravel query builder, get count of child rows that meet a certain condition, for each record in parent table?
I have a users
table and a messages
table that stores messages that users send to each other. 我有一个
users
表和一个messages
表,用于存储用户相互发送的消息。 users table: 用户表:
-------------------
|id|name |lastName|
|------------------|
|1 |emma |watson |
|2 |taylor|swift |
|3 |tiger |woods |
massages table: 按摩台:
|id|messageBody|from_id|to_id|isRead|
|-----------------------------------|
|1 |... |1 |2 |0 |
|2 |... |2 |3 |1 |
|3 |... |1 |3 |0 |
what I seek is to get the list of all users and count of unread messages that they have send to current user,which in laravel is reached by auth()->user(). 我想要的是获取所有用户的列表以及他们已发送给当前用户的未读邮件的数量,在laravel中,它们是通过auth()-> user()到达的。 I realized that sql query for this is sth like this:
我意识到这样做的SQL查询是这样的:
SELECT users.id,users.name,users.lastName,(select count(*)
from messages where messages.from_id = users.id and messages.to_id =1 and
messages.isRead = 0) as countOfNewMessages FROM users
but how can I reach this result with laravel's query builder? 但是如何使用laravel的查询生成器达到此结果?
The classic method is 经典方法是
// messages
$messages = Messages::where('isRead',0)->where('to_id',auth()->user()->id)->get();
//count of messages
$count = $messages->count();
But you also can use relations
to get messages of users and their count. 但是,您也可以使用
relations
来获取用户消息及其人数。 Please follow Laravel:Relations 请关注Laravel:关系
On your Messages Model 在您的消息模型上
public function user(){
return $this->belongsTo('App\User','to_id','id');
}
On your Controller 在您的控制器上
//For All Data
$messages = Messages::with('user')->where(['isRead'=>0,'to_id'=>1])->get();
//For Count Data
you can easily check how much unread message by `count($messages)`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.