robsonvleite / datalayer

The data layer is a persistent abstraction component of your database that PDO (O data layer é um componente para abstração de persistência no seu banco de dados que usa PDO com prepared statements)
https://www.upinside.com.br
MIT License
144 stars 53 forks source link

Add Join feature to DataLayer for 1-N and N-N relationships (with examples) #29

Closed ruifernandees closed 3 years ago

ruifernandees commented 4 years ago

Now, the DataLayer has a join method, which is called with 'select' and 'where' methods. Here is an example: Agora, o DataLayer possui um método para join, o qual se chama junto dos métodos 'select' e 'where'. Aqui está um exemplo:

1-N Relationship: (example/Models/Course.php)

    /**
     * @return array|null
     */
    public function studentsWhoPrefer(): ?array
    {
        $students = new Student();
        return $this
            ->select("*, courses.name as course_name")
            ->join(
                $students, 
                'courses.id', '=', 'students.preferred_course')
            ->where(
                'courses.id = :id', 
                "id={$this->id}")
            ->limit(5)
            ->fetch(true);
    }

N-N Relationship: (example/Models/Student.php)

    public function doneCourses(): ?array
    {
        $courses = new Course();
        $studentCourse = new StudentCourse();

        return $this
            ->select("*, students.name as student_name")
            ->join(
                $studentCourse,
                "students.id", "=", "student_course.idstudent"
            )
            ->join(
                $courses,   
                "courses.id", "=", "student_course.idcourse"
            )
            ->where(
                "student_course.idstudent = :id",
                "id={$this->id}"
            )
            ->fetch(true);
    }