繁体   English   中英

Laravel范围模型从关系计数

[英]Laravel scope model count from relationship

我正在尝试计算对话中的未读邮件。 这是我的表结构。

mysql> describe conversations;
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |                             |
| other fields which are not needed            
+-------------+------------------+------+-----+---------+----------------+
6 rows in set (0,00 sec)

mysql> describe messages;
+-----------------+------------------+------+-----+-------------------+-----------------------------+
| Field           | Type             | Null | Key | Default           | Extra                       |
+-----------------+------------------+------+-----+-------------------+-----------------------------+
| id              | int(10) unsigned | NO   | PRI | NULL              | auto_increment              |
| is_seen         | tinyint(1)       | NO   |     | NULL              |                             |                         |
| conversation_id | int(10) unsigned | NO   | MUL | NULL              |                             |
+-----------------+------------------+------+-----+-------------------+-----------------------------+

表之间的关系运行良好:

//Conversation.php 
// this return all messages from the conversation
public function messages(){
        return $this->hasMany('App\Message','conversation_id');
    }


// I got stuck in this function
public function scopeUnread($query){
        return $query->whereHas('messages', function($q){
            $q->where('is_seen',0);
        });
    }

我正在尝试计算对话中所有未读的消息,我做了上面的功能,所以我可以像这样从对话中获取未读的数量

Conversation::find(1)->unread();

您需要在结束查询之前调用作用域(在您的情况下->find(1)之前->find(1)

像这样:

Conversation::unread()->find();

编辑:Nvm,我不明白你想要什么。

这是您计算会话中未读邮件的方式:

$c = Conversation::find(1);
$unreadCount = $c->messages()->where('is_seen', 0)->count();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM