Reputation: 327
I have a model class with the name CourseSession
and it's table is course_session
, and I have another model named Student
and it's table is student
and every session has many students and also every student could be in many sessions. So I have created a third table named student_session
with student_id
, session_id
, presence
and laravels timestamp columns.
Creating a session needs to have a list of students and I get them from $request
like this:
$validatedData = $request->validate([
'students' => 'required',
]);
students
is array of students id!
this is my CourseSession
model:
class CourseSession extends Model
{
protected $table = 'course_sessions';
protected $guarded = [];
public function course()
{
return $this->belongsTo('App\Course');
}
public function students()
{
return $this->belongsToMany('App\Student', 'student_session','session_id', 'student_id');
}
}
and this is my student model:
class Student extends Model
{
protected $guarded = [];
public function courses()
{
return $this->belongsToMany('App\Course');
}
public function exams()
{
return $this->belongsToMany('App\Exam');
}
public function sessions()
{
return $this->belongsToMany('App\CourseSession', 'student_session', 'student_id', 'session_id');
}
}
I create a session like this:
$session = new CourseSession();
$session->course_id = $course->id;
$session->save();
and I save students this way:
$sessions = $session->students()->create(['session_id' => $session->id, 'student_id' => 1, 'presence' => 1]);
but I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'session_id' in 'field list' (SQL: insert into `students` (`session_id`, `student_id`, `presence`, `updated_at`, `created_at`) values (25, 1, 1, 2019-04-28 14:24:48, 2019-04-28 14:24:48))
according to error, it tries to write data on students
table but I want to write them on student_session
table!
what is wrong in my codes?
Upvotes: 0
Views: 529
Reputation: 35170
For this you want to use attach() instead of create()
.
$session->students()->attach(1, ['presence' => 1]);
In the above example 1
is the student_id
. You don't need to specify the session_id
as your calling this from a Session
model. The array at the end is any additional data you want to add to the pivot table.
Since you have additional data in your student_session
pivot table, it might also be an idea to add this to your belongsToMany
relationships e.g.
public function sessions()
{
return $this->belongsToMany('App\CourseSession', 'student_session', 'student_id', 'session_id')
->withPivot('presence')
->withTimestamps();
}
This will include the presence
and timestamps columns in the pivot data as well (obviously, you don't have to do this if you don't want to though).
Upvotes: 1