繁体   English   中英

如何在laravel雄辩的地方使用条件

[英]How to use where condition in laravel eloquent

我在用laravel雄辩。 我已经雄辩地从两个表中获取了数据。 我有post表和chat表。 对于post表,我具有模型Post.php ;对于chat表,我具有模型Chat.php 这是我创建的雄辩的关系,用于为用户获取单个帖子的聊天记录。

Post.php

public function TeamMessage()
{
  return $this->hasMany('App\Chat','post_id');
}

并在Chat.php

public function ChatRelation()
{
    return $this->belongsTo('App\Post');
}

它工作完美。 但是,此关系获取特定帖子的所有消息。 我想从chat表中获取所有未读消息。 我在chat表中有一列unread 现在,我的问题是如何只获取特定帖子的unread消息。

尽管其他答案都能正常工作,但它们要么取决于作用域(在许多情况下非常有用),要么取决于您已经实例化了$post实例,这不允许您急于将其消息加载到多个帖子中。

动态解决方案是这样,它使您可以提取1个或多个帖子,并渴望通过子查询加载其消息:

$posts = Post::with(['TeamMessage' => function ($query) {
    $query->where('unread', true); // This part applies to the TeamMessage query
}])->get();

参见文档

编辑:

但是,如果要过滤帖子,以仅显示未读邮件,则需要使用whereHas而不是with

$posts = Post::whereHas(['TeamMessage' => function ($query) {
    $query->where('unread', true); // This part applies to the TeamMessage query
}])->get();

在文档中有更多内容

您还可以将whereHas(...)with(...)

对于查询关系,必须将它们作为函数而不是属性来调用,如下所示:

$unreadPosts = $post->TeamMessage()->where('unread', true)->get();

有关此的更多信息,请查看docs

您需要在模型上创建局部范围,有关局部范围的信息可以在这里找到: https : //laravel.com/docs/5.6/eloquent#local-scopes

 public function scopeUnread($query)
{
    return $query->where('unread', 1);
}

然后在您的控制器/视图中

$unread = $yourmodel->unread()

首先,我将您的关系名称更改为小写的实体名称:

在Post.php中

public function chats()
{
    return $this->hasMany('App\Chat','post_id');
}

并在Chat.php中

public function post()
{
    return $this->belongsTo('App\Post');
}

public function scopeUnread($query)
{
    return $query->where('unread', 1);
}

那你可以用

$post->chats()->unread()->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM