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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭