Laravel Eloquent 不能用where not查询关系

Laravel Eloquent can't use where not to query relationship

我的问题: 我似乎无法在使用 Laravel 的 Eloquent ORM 的关系集合上使用 where('user_id', '<>', Auth::id()

在 Laravel 5 中,我有一个具有以下架构的数据库:

| USERS    | JOBS    | CONVERSATIONS | MESSAGES        | CONVERSATION_USER |
| id       | id      | id            | id              | conversation_id   |
| username | user_id | job_id        | conversation_id | user_id           |
| password | title   |               | user_id         |                   |
|          |         |               | message         |                   |

并具有以下关系:

User model:
$jobs = $this->hasMany('job');
$messages = $this->hasMany('message');
$conversations = $this->belongsToMany('conversation');

Job model:
$user = $this->belongsTo('user');
$conversations = $this->hasMany('conversation');
$messages = $this->hasManyThrough('message', 'conversation');

Conversation model:
$job = $this->belongsTo('job');
$messages = $this->hasMany('message');
$user = $this->belongsToMany('user');

Message model:
$user = $this->belongsTo('user');
$conversation = $this->belongsTo('conversation');

我正在尝试获取作业的消息数,这些消息尚未由经过身份验证的用户发布。我的代码是:

// Load all of the jobs which relate to the logged in user
$jobs = Job::with(['messages'])->where('user_id', Auth::id())->OrderBy('id', 'DESC')->get();

foreach ($jobs as $job)
{
    // Count all messages that have not been sent by the logged in user
    echo $job->messages->where('user_id', '<>', Auth::id())->count().'<br />';
}

但是我就是无法使用计数功能。

如果您在循环中将 messages-> 更改为 message()->,您将能够重新查询您的关系集。