Php 仅显示不在其他表laravel中的项目

Php 仅显示不在其他表laravel中的项目,php,laravel,Php,Laravel,我只想展示那些不受欢迎的学校 要得到我喜欢的,我使用: $favorite_schools = DB::table('favorite_schools') ->select('favorite_schools.*', 'schools.name') ->leftJoin('schools', 'schools.id', 'favorite_schools.school_i

我只想展示那些不受欢迎的学校

要得到我喜欢的,我使用:

 $favorite_schools = DB::table('favorite_schools')
                            ->select('favorite_schools.*', 'schools.name')
                            ->leftJoin('schools', 'schools.id', 'favorite_schools.school_id')
                            ->get();
学校表:

Schema::create('schools', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('active');
        $table->timestamps();
    });
最喜爱的学校表:

 Schema::create('favorite_schools', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('school_id');
        $table->timestamps();
    });

我怎么能只得到那些还没有得到青睐的学校呢?

你需要走另一条路。获取学校,并在favorites表中左键联接,然后获取favorite_schools表中没有结果的结果

$favorite_schools = DB::table('schools')
                        ->select('schools.name', 'schools.id')
                        ->leftJoin('favorite_schools', 'schools.id', 'favorite_schools.school_id')
                        ->whereNull('favorite_schools.school_id')
                        ->get();
WhereNull('favorite\u schools.school\u id')
添加到用于获取收藏夹的查询中。这会给你带来不喜欢的学校


祝你好运

稍微不同的方法是使用不存在的

用法如下:

$schools = DB::table('schools')
    ->whereNotExists(function ($query) {
        $query->select(DB::raw(1))
              ->from('favorite_schools')
              ->whereRaw('favorite_schools.school_id = school.id');
    })
    ->get();

我不熟悉Laravel语法,但一般来说,要查找相关表中没有行的行,需要一个外部联接,其中联接的表为null。