Laravel Eloquent不能用于不查询关系的地方

时间:2015-04-27 09:27:28

标签: php mysql laravel eloquent

我的问题:我似乎无法使用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 />';
}

但是我无法让计数功能起作用。

1 个答案:

答案 0 :(得分:0)

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