Laravel關係我有3個表:具有樞軸表
類別(ID,姓名)
Category_Tournament(CATEGORY_ID,tournament_id) - >樞軸表 Category_Tournament_User(CATEGORY_ID,tournament_id,USER_ID,確認)
類別可用類別列表 Category_Tournament是管理員配置 Category_tournament_User是用戶registred
類別類別列表10要獲得在比賽中的所有類別,我可以很容易地做到這一點:
tournament->categories
定義在比賽模型belongsToMany關係
我不知道什麼如何與最後一個表中定義的關係。
我需要的是幾類用戶點擊,我可以運行類似:
tournament->user_categories->sync($userCategories)
,我應該同步表Category_Tournament_User(與CATEGORY_ID,tournament_id,USER_ID)
什麼最好的辦法來實現它?
編輯:
型號錦標賽:
class Tournament extends Model
{
protected $table = 'tournament';
public $timestamps = true;
protected $fillable = [
'name',
'date',
'type',
];
/**
* A tournament is owned by a user
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function owner()
{
return $this->belongsTo('App\User', 'user_id','id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function categories()
{
return $this->belongsToMany('App\Category')
->withTimestamps();
}
}
型號類別
class Category extends Model
{
protected $table = 'category';
public $timestamps = true;
protected $fillable = [
'id',
'name',
];
public function tournaments()
{
return $this->belongsToMany('App\Tournament');
}
}
型號用戶:
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, HasRole;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','firstname','lastname','email', 'password','avatar',country_id','role_id',,'provider','provider_id','verified'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Boot the model.
*
* @return void
*/
public static function boot()
{
parent::boot();
static::creating(function ($user) {
$user->token = str_random(30);
});
}
public function role()
{
return $this->belongsTo('App\Role');
}
public function settings()
{
return $this->hasOne('App\Settings');
}
public function invites()
{
return $this->hasMany('App\Invite', 'email','email');
}
public function country()
{
return $this->belongsTo('Webpatser\Countries\Countries');
}
/**
* A user can have many tournaments
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function tournaments()
{
return $this->hasMany('App\Tournament');
}
}
是的,但我的問題是Category_Tournament作爲複合PK –
多一點幫助,將不勝感激!我已經在這個問題上花費了2天時間,並且很難用2條線解決問題。 –
好吧給OP添加模型。 –