2
我提出了一個查詢,但我並不滿意,因爲我想用Eloquent來做!在Laravel 5.2中使用雄辯而不是查詢
下面是該查詢:
Tournament::leftJoin('category_tournament', 'category_tournament.tournament_id', '=', 'tournament.id')
->leftJoin('category_tournament_user', 'category_tournament_user.category_tournament_id', '=', 'category_tournament.id')
->where('category_tournament_user.user_id', '=',$this->id)
->select('tournament.*')
->distinct()
->get();
遷移:
Schema::create('tournaments', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('categories', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('category_tournament', function(Blueprint $table) {
$table->increments('id');
$table->integer('category_id');
$table->integer('tournament_id');
$table->timestamps();
$table->foreign('tournament_id')
->references('id')
->on('tournament')
->onDelete('cascade');
$table->foreign('category_id')
->references('id')
->on('category')
->onDelete('cascade');
});
Schema::create('category_tournament_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_tournament_id')->unsigned()->index();
$table->foreign('category_tournament_id')
->references('id')
->on('category_tournament')
->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->unique(array('category_tournament_id', 'user_id'));
$table->boolean('confirmed');
$table->timestamps();
$table->softDeletes();
$table->engine = 'InnoDB';
});
模型
class Tournament extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
public function categoryTournaments()
{
return $this->hasMany(CategoryTournament::class);
}
}
class Category extends Model
{
public function tournaments()
{
return $this->belongsToMany(Tournament::class);
}
public function categoryTournament()
{
return $this->hasMany(CategoryTournament::class);
}
}
class CategoryTournament extends Model
{
protected $table = 'category_tournament';
public function category()
{
return $this->belongsTo(Category::class);
}
public function tournament()
{
return $this->belongsTo(Tournament::class);
}
public function users()
{
return $this->belongsToMany(User::class, 'category_tournament_user');
}
}
class User extends Authenticatable
{
public function categoryTournaments()
{
return $this->belongsToMany(CategoryTournament::class, 'category_tournament_user');
}
}
的查詢工作,我只是想知道我應該怎麼用雄辯這樣做是因爲我無法自己做:(
任何想法如何做?
對不起,我忘記在我的答案中包含FK。你的答案有兩個問題:1.你從不過濾當前用戶的結果(相當於我的查詢中的 - > where('category_tournament_user.user_id','=',$ this-> id) )。 2.與$錦標賽 - > category_tournament->名稱,每個錦標賽我將不得不作出額外的查詢,所以我應該做n + 1查詢,這是我想避免的... –
1:我不'我認爲你的where子句有其他選擇。您可以將其添加到查詢中。 2 .:我編輯了我的答案,以添加一個連接到急切的加載。應該是你的第二個問題的答案。 –