Laravel的querybuilder选择id不在另一个表中的位置

时间:2019-10-17 07:22:59

标签: php mysql laravel eloquent

我在subscriptionsschool上有两个表格,我只想选择尚未订阅的学校。我引用了学校id。有人可以在laravel的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 ▶}
  ]
}

3 个答案:

答案 0 :(得分:2)

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

在您的School模型中定义关系

public function subscriptions()
{
    return $this->hasMany('App\Subscription','school_id'); // path of Subscription model
}

查询以获取具有订阅的学校:

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

答案 1 :(得分:1)

使用.everyMinutes(4)获取另一个表中不存在的学校。

whereNotIn

答案 2 :(得分:1)

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