, .
users teams. particpatable_id particpatable_type, id timestamps().
competition_participant, competitions participants.
participants competitions. , , $participant->participatable, App\User, App\Team .
.
public function up()
{
Schema::create('competitions', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('teams', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('participants', function(Blueprint $table) {
$table->increments('id');
$table->integer('participatable_id');
$table->string('participatable_type');
$table->timestamps();
});
Schema::create('competition_participant', function(Blueprint $table) {
$table->integer('competition_id');
$table->integer('participant_id');
});
}
class Competition extends Model
{
public function participants()
{
return $this->belongsToMany(Participant::class);
}
}
class Participant extends Model
{
public function participatable()
{
return $this->morphTo();
}
public function competitions()
{
return $this->belongsToMany(Competition::class);
}
}
class Team extends Model
{
public function participants()
{
return $this->morphMany(Participant::class, 'participatable');
}
}
class User extends Authenticatable
{
public function participants()
{
return $this->morphMany(Participant::class, 'participatable');
}
}
public function run()
{
$faker = Faker\Factory::create();
DB::table('users')->delete();
$users = [];
for($i = 0; $i < 100; $i++) {
$users[] = [
'name' => $faker->name,
'email' => $faker->email,
'password' => Hash::make($faker->password),
'created_at' => new DateTime,
'updated_at' => new DateTime
];
}
DB::table('users')->insert($users);
DB::table('teams')->delete();
$teams = [];
for($i = 0; $i < 20; $i++) {
$teams[] = [
'name' => 'Team ' . ucwords($faker->domainWord),
'created_at' => new DateTime,
'updated_at' => new DateTime
];
}
DB::table('teams')->insert($teams);
DB::table('participants')->delete();
$users = App\User::limit(20)->orderByRaw('rand()')->get();
foreach($users as $user) {
$user->participants()->create([]);
}
$teams = App\Team::limit(10)->orderByRaw('rand()')->get();
foreach($teams as $team) {
$team->participants()->create([]);
}
DB::table('competitions')->delete();
$competitions = [];
for($i = 0; $i < 10; $i++) {
$competitions[] = [
'name' => $faker->company,
'created_at' => new DateTime,
'updated_at' => new DateTime,
];
}
DB::table('competitions')->insert($competitions);
DB::table('competition_participant')->delete();
$participants = App\Participant::all();
$competitions = App\Competition::all();
foreach($participants as $participant) {
$participant->competitions()->sync($competitions->shuffle()->take(3));
}
}
$competition = App\Competition::with('participants')->has('participants')->first();
foreach($competition->participants as $participant) {
echo get_class($participant->participatable);
echo "<br />";
}