[英]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.