我只想显示不受欢迎的学校。
得到我喜欢的东西:
$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();
});
Favorite_schools表:
Schema::create('favorite_schools', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('school_id');
$table->timestamps();
});
我如何才能只获得尚未被收藏的学校?
答案 0 :(得分:1)
您需要走另一条路。获取学校,然后在“收藏夹”表上保留联接,然后获取在“ favourite_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();
答案 1 :(得分:0)
将WhereNull('favorite_schools.school_id')
添加到用于获取喜欢的查询的查询中。那会给你不受欢迎的学校。
祝你好运
答案 2 :(得分:0)
一种稍微不同的方法是使用whereNotExists
,它应该比使用联接要快
用法将是这样的:
$schools = DB::table('schools')
->whereNotExists(function ($query) {
$query->select(DB::raw(1))
->from('favorite_schools')
->whereRaw('favorite_schools.school_id = school.id');
})
->get();