Laravel 4:不存在的地方

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22409469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:11:43  来源:igfitidea点击:

Laravel 4: Where Not Exists

phpmysqllaraveleloquent

提问by sterfry68

I need my model to return only those records from one table where a matching record does not exist in another table. I was thinking that the solution might be with Query Scopesbut the documentation only scratches the surface. So my SQL would look something like this:

我需要我的模型只返回一个表中的那些记录,而另一个表中不存在匹配的记录。我在想解决方案可能与查询范围有关,但文档只是触及了表面。所以我的 SQL 看起来像这样:

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

Here are my tables:

这是我的表:

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

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

Probably unnecessary but here are my models. Model for A:

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

class A extends Eloquent{

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

Model for B:

B 型号:

class B extends Eloquent{

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

回答by marcanuy

Something like

就像是

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