Laravel范围模型从关系计算

时间:2017-08-27 18:46:05

标签: php mysql laravel

我正在尝试计算来自对话的未读消息。这是我的表结构。

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();

1 个答案:

答案 0 :(得分:2)

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

像这样:

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

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

这就是你如何计算来自对话的未读消息:

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