php - Eloquent 查询 1 :n relationship

标签 php mysql laravel eloquent

我的数据库中有 2 个表,一个是 notifications 表,一个是 notifications_user 表。

一个通知可以有多个通知用户。在我的通知模型中,我有以下关系的结果,

public function user()
{
    return $this->belongsToMany('User')->withPivot('is_read');
}

我想要实现的是获取所有未读通知(或 is_read = 0),但 is_read 列在通知用户表中,因此我不知道如何对其运行查询。

目前我有这个,

$unread = Notification::has('user')->with('user')->get();

现在这将关系拉入结果,但不考虑 is_read 值。

有没有一种方法可以根据 1:n 关系中的值从表中选择所有数据。

最佳答案

您可以通过执行以下操作来查询关系:

$unread = Notification::has('user')->with('user')->where('is_read','!=', 0)->get();

查看文档:http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

关于php - Eloquent 查询 1 :n relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612083/

相关文章:

php - Swagger 的 laravel 护照不起作用

php - 与映射父类(super class)的关联映射

php - 给定字符串模型时,Laravel Eloquent Find 不起作用

mysql - 导出的 blob 数据不同于数据库数据

javascript - 列表项中的jquery id?

php - laravel Eloquent 数组到字符串的转换

PHP DOM loadHtmlFile I/O 异常

c# - 将 MYSQL 数据库中的数据显示到控件,尤其是在 DropDown 的 Combobox 上

jquery - 使用 ajax 发布数据的日期范围选择器

php - 有什么办法可以从服务器恢复已删除的 .env laravel 文件