I update all pivot records

-1

In Laravel 5.4 I'm trying to save the contents of an N: M relationship in a pivot, the problem I have is that it updates all the records that are related to that id, it's like I did an update with the where of the id of the student.

The code:

$alumnos = Alumnos::obtenerAlumnosAsignaturas();
foreach($alumnos as $alumno){
 if($alumno->pivot->asignatura == null){
  $alumno->pivot->asignatura = 0;
  $alumno->pivot->save();
 }
}

The two tables

| id | alumno| |id|asignaturas |
|----|-------| |--|------------|
| 1  | Juan  | | 1| Matemáticas|
| 2  | Pepe  | | 2| Lengua     |
| 3  | Luis  | | 3| Inglés     |
|----|-------| |--|------------|

Pivot

| id | asignatura_id | alumno_id |
|----|---------------|-----------|
| 1  | 1             | 1         |
| 1  | 1             | 2         |
| 3  | 3             | 3         |

After executing the code, it goes to:

| id | asignatura_id | alumno_id |
|----|---------------|-----------|
| 1  | 1             | 0         |
| 2  | 1             | 0         |
| 3  | 3             | 3         |
    
asked by CodeNoob 25.08.2017 в 17:17
source

1 answer

0

I have solved it.

// Obtenemos todos los alumnos con sus corrrespondientes asignaturas
$alumnos = Alumnos::obtenerAlumnosAsignaturas();
// Los recorremos
foreach($alumnos as $alumno){
 // Si encontramos un registro del alumno de su asignatura a null 
 if($alumno->pviot->asignatura == null){
  // Accedo a la pivote , por medio de mi modelo en la N:M
  $pivote = AlumnosAsignaturas::findOrFail($alumno->pivot->id);
  $pivote->asignatura = 0;
  $pivote->save();
 }
}

Now I explain:

What I did was create a model for the pivot table that comes from the N: M, of students and subjects, because in a subject there can be more than one student and a student can belong to more than one subject, more than it may be the case that the field may not be covered, where it would be set to null, which in turn is a problem in the design of the database.

Models:

Alumnos -------> AlumnosAsignaturas <------- Asignaturas

I hope this helps future people who have this error. Do not put negatives by not understanding the question. It would be appreciated.

    
answered by 29.08.2017 / 11:18
source