I have a one to many relationship set up between two tables: camps (one) and sessions (many). There is one camp and it can have many sessions dates/times. When I create a camp, and related sessions, Eloquent stores a duplicate camp record for every session that I add. So, if I create one camp and one session, then everything is great. However, if I create one camp with 2 sessions, then Eloquent will create 2 identical records in the camps table.
Not the desired outcome; it should be one camp and 2 session. Any ideas as to why this is happening? Thank you.
Controller Create Method
var_dump($dynamicSessions); die('dead');
array (size=1)
1 =>
array (size=4)
'start_date' =>
object(Carbon\Carbon)[209]
public 'date' => string '2019-08-20 00:00:00.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
'end_date' =>
object(Carbon\Carbon)[211]
public 'date' => string '2019-08-25 00:00:00.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
'start_time' =>
object(Carbon\Carbon)[204]
public 'date' => string '2017-01-12 09:00:00.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
'end_time' =>
object(Carbon\Carbon)[212]
public 'date' => string '2017-01-12 12:00:00.000000' (length=26)
public 'timezone_type' => int 3
public 'timezone' => string 'UTC' (length=3)
end
try {
$camp->sessions()->saveMany($dynamicSessions);
} catch (Exception $e) {
Log::error(
'1LN100: Error while saving entry: ' . $e->getMessage(),
array_merge($this->logVariables, $request->all())
);
throw new Exception('Error 1LN100: Failed to save entry.');
}
Log::debug(
'1LN108: Saved entry',
array_merge($this->logVariables, $request->all())
);
Migration file 1 (Camps):
Schema::create('camps', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
Migration file 2 (Sessions):
Schema::create('camp_sessions', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('camp_id')->unsigned();
$table->timestamp('start_date')->nullable();
$table->timestamp('end_date')->nullable();
$table->timestamp('start_time')->nullable();
$table->timestamp('end_time')->nullable();
});
Schema::table('camp_sessions', function (Blueprint $table) {
$table->foreign('camp_id')->references('id')->on('camps')->onDelete('cascade');
});
Model for Migration 1 (Camps):
protected $fillable = [
'field',
'field',
'field',
];
public function sessions()
{
return $this->hasMany('App\CampSession');
}
Model for Migration 2 (Sessions):
protected $fillable = [
'start_date',
'end_date',
'start_time',
'end_time'
];
public function camps()
{
return $this->belongsTo('App\Camp');
}