[英]Select all records from one table that do not exist in another table in Laravel 5.1
I want to get all the records from a table which do not exist in other table in Laravel 5.1.我想从 Laravel 5.1 的其他表中不存在的表中获取所有记录。
I know how to do this in core php, and it works fine with the following code我知道如何在核心 php 中执行此操作,并且使用以下代码可以正常工作
SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL
the model该模型
public function audiences()
{
return $this->belongsTo('App\BridalRequest', 'request_id');
}
but when i try to do the same in Laravel by using the following code,但是当我尝试使用以下代码在 Laravel 中执行相同操作时,
$all_bridal_requests_check = \DB::table('bridal_requests')
->where(function($query)
{
$query->where('publisher', '=', 'bq-quotes.sb.com')
->orWhere('publisher', '=', 'bq-wd.com-bsf');
})
->whereNotIn('id', function($query) { $query->table('audiences')->select('request_id'); })
->orderBy('created_on', 'desc')
->get();
then it gives me this error然后它给了我这个错误
Call to undefined method Illuminate\\Database\\Query\\Builder::table()
调用未定义的方法 Illuminate\\Database\\Query\\Builder::table()
The above mentioned query can be built using laravel query builder in the following manner.可以通过以下方式使用 laravel 查询构建器构建上述查询。
SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL
This is equivalent to below query built using Laravel's query builder.这相当于使用 Laravel 的查询构建器构建的以下查询。
\DB::table('table1 AS t1')
->select('t1.name')
->leftJoin('table2 AS t2','t2.name','=','t1.name')
->whereNull('t2.name')->get();
Late but yes I would like to add into this question.迟到了,但是我想补充这个问题。 Create laravel eloquent relationship between table by writing below code in
users
model file,通过在
users
模型文件中编写以下代码,在表之间创建 Laravel eloquent 关系,
public function mu_user()
{
return $this->hasMany(\App\MainUser::class, 'id');
}
Now get all records from users table which does not have main user in relation as below,现在从没有主要用户关系的用户表中获取所有记录,如下所示,
$users = Users::doesnthave('mu_user')->get();
If you want to get users who have main_users then you can write query as below,如果你想获得拥有 main_users 的用户,那么你可以编写如下查询,
$users = Author::has('mu_user')->get();
It's such easy.这太容易了。 Hope it helps!
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.