php - 拉维尔 4 : Where Not Exists

标签 php mysql laravel eloquent

我需要我的模型仅从一个表中返回那些匹配记录在另一个表中不存在的记录。我在想解决方案可能是 Query Scopes但文档只涉及表面。所以我的 SQL 看起来像这样:

SELECT *
FROM A
WHERE NOT EXISTS (SELECT A_id FROM B
                WHERE B.A_id = A.id)

这是我的表格:

A
-------------
| id | name |
-------------

B
--------------------
| id | A_id | name |
--------------------

可能没有必要,但这是我的模型。 A 的模型:

class A extends Eloquent{

    public function B(){
        return $this->hasOne('B', 'A_id', 'id');
    }
}

B 的模型:

class B extends Eloquent{

    public function A(){
        return $this->belongsTo('B', 'A_id', 'id');
    }
}

最佳答案

有点像

A::whereNotExists(function($query)
            {
                $query->select(DB::raw(1))
                      ->from('B')
                      ->whereRaw('A.id = B.id');
            })
            ->get();

关于php - 拉维尔 4 : Where Not Exists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22409469/

相关文章:

java - 使用 php 和 JSON 将 android 连接到 mySQL

PHP exec(node) 仅针对 -v 运行,但不适用于 .js 文件

javascript - 如何在 PHP 中为 WordPress 插件编写 JavaScript 代码

mysql - fatal error : require_once() [function. 需要] : Failed opening required global. php

java - 与访问 mysql 数据库中的相同数据相比,访问 java 列表(arraylist)是否更快?

JavaScript 变量在 Laravel 中不起作用

php - 播种机命令不工作 Laravel 5.4

php - 更新期间验证用户电子邮件字段

PHP 比较运算符在 MySQL streak 查询中不起作用

javascript - 通过在页面末尾添加按钮自动将我的网页内容转换为pdf