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 .:我编辑了我的答案,以添加一个连接到急切的加载。应该是你的第二个问题的答案。 –