Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/256.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 拉维尔';s querybuilder选择id不在另一个表中的位置_Php_Mysql_Laravel_Eloquent - Fatal编程技术网

Php 拉维尔';s querybuilder选择id不在另一个表中的位置

Php 拉维尔';s querybuilder选择id不在另一个表中的位置,php,mysql,laravel,eloquent,Php,Mysql,Laravel,Eloquent,这里有两个表订阅和学校,我只想选择尚未订阅的学校。我引用了学校id。有人能在拉威尔的querybuilder里帮我吗 我当前的代码 $schools = \DB::table('schools') ->leftJoin('subscriptions', 'subscriptions.school_id', '=', 'schools.id') ->select('sc

这里有两个表
订阅
学校
,我只想选择尚未订阅的学校。我引用了学校
id
。有人能在拉威尔的querybuilder里帮我吗

我当前的代码

  $schools = \DB::table('schools')
                          ->leftJoin('subscriptions', 'subscriptions.school_id', '=', 'schools.id')     
                          ->select('schools.*','subscriptions.status')
                          ->get();
    dd($schools);

学校表

+----+------+-----------------+
| id | name | description     |
+----+------+-----------------+
|  1 | SAFE | Safe University |
|  2 | MND  | DEMO UNIVERSITY |
|  3 | Test | Test 1          |
|  4 | X    | Test 2          |
+----+------+-----------------+
订阅表

+----+-----------+------------+------------+---------+--------+
| id | school_id | start_date | end_date   | plan_id | status |
+----+-----------+------------+------------+---------+--------+
|  1 |         1 | 2019-10-20 | 2019-11-30 |       1 |      1 |
|  2 |         2 | 2019-09-27 | 2019-10-27 |       1 |      0 |
+----+-----------+------------+------------+---------+--------
当我
dd
时,我得到了4所学校

Collection {#796 ▼
  #items: array:4 [▼
    0 => {#762 ▶}
    1 => {#799 ▶}
    2 => {#803 ▶}
    3 => {#839 ▶}
  ]
}

使用
whereNotIn
获取其他表中不存在的学校

DB::table('schools')
    ->whereNotIn('id', DB::table('subscriptions')->pluck('school_id'))
    ->get();

您可以定义学校和订阅的关系:

$schools = School::with('subscriptions')->doesnthave('subscriptions')->get();
在您的
学校
模型中定义关系

public function subscriptions()
{
    return $this->hasMany('App\Subscription','school_id'); // path of Subscription model
}
查询以获取已订阅的学校:

$schools = School::with('subscriptions')->doesnthave('subscriptions')->get();

我试过了,但正好相反。我得到了两个订阅的学校。使用
whereNotExists
检查更新的答案。我得到了这个错误,先生
Non-static method illumb\Database\Query\Builder::whereNotExists()不应该静态调用
尝试更新的答案。哇,谢谢你的回答。你能给我解释一下吗?我得到了一个空结果sir如何在querybuilder中实现吗sir?对于查询生成器,你可以使用@Laravel answerPerfect way处理关系。谢谢,@YasinPatel感谢查询生成器。