doushi5913 2015-04-27 09:27
浏览 77
已采纳

Laravel Eloquent不能使用哪里不查询关系

My problem: I can't seem to use where('user_id', '<>', Auth::id() on a relationship collection using Laravel's Eloquent ORM.

In Laravel 5, I have a database with the following schema:

| 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         |                   |

and with the following relationships:

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

I'm trying to get the number of messages for a job, which have not been posted by the authenticated user. My code is:

// 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 />';
}

However I just cannot get the count function to work.

  • 写回答

1条回答 默认 最新

  • doudu9094 2015-04-28 09:41
    关注

    If you change messages-> to message()-> within your loop, you will be able to re-query your relation set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏