1
I have a polymorphic m-m relationship in my bank where:
class(id, name)
student(id, name)
Lesson(id, name)
classeable(classe_id, classeable_id, classeable_type)
a class has several Students and several lessons. a student can be in several classes and watch several lessons a Lesson can be in several classes and be assisted by several Students
When a student attends a Lection a result is generated and in these results I want to include the name of the class the student participates in for which he attended Lection. I don’t know how to build this query in the Standard using this relationship structure in the database.
Edit 1:
Classe extends model {
public function students() {
return $this->morphedByMany(Student::class, 'classeable');
}
public function lessons() {
return $this->morphedByMany(Lesson::class, 'classeable');
}
}
Student extends model {
public function classes(){
return $this->morphToMany(Classe::class, 'classeable');
}
}
Lesson extends model {
public function classes(){
return $this->morphToMany(Classe::class, 'classeable');
}
}
If you don’t know how to create relationships or you’ve created relationships?
– novic
in the Class.php model I created like this: public Function Students() { Return $this->morphedByMany(Student::class, 'classeable'); } public Function lessons() { Return $this->morphedByMany(Lesson::class, 'classeable'); }
– Ygor Dutra
and in the Students and lessons classes I created: public Function classes(){ Return $this->morphToMany(Class::class, 'classeable'); }
– Ygor Dutra
if you could put what you did? because when you record the information the type of class goes by relationship.
– novic
I put Edit 1
– Ygor Dutra
You don’t understand how you record information?
– novic
I don’t understand how I can recover the class that has a student x and a student y. I don’t know if I can be clear.
– Ygor Dutra
So, it looks like the relationships are right, to retrieve the information is the same thing as
$aluno = Student::find(1);
and$aluno->classes()->get()
. there’s no difference how to use it the same way as another kind of relationship, is that your doubt?– novic
More or less that... So, imagine that I could have made this relation with the tables classe_lesson (classe_id, lesson_id) and classe_student(classe_id, student_id). Then for me to retrieve the information I want I could make a select in the class using Join in classe_lesson (lesson_id) and another Join in classe_student (student_id). I just don’t know how to do it on the Laravel.
– Ygor Dutra
Ygor, in the relationship he already does it for you, in a transparent way, a question whether you tested the way I said if yes what happened:?
– novic
I tested, it returns me a list of all classes of the student
– Ygor Dutra
Maybe you’re saving wrong. How are you saving?
– novic
Possible duplicate of Multi-table heritage in Laravel
– novic