Friday, July 31, 2015

Re: CakePHP 3 - hasMany through association

Try:

$query = $this->Courses->find('all')
                       ->contain(['Students', 'CourseMemberships'])
                       ->where(['Students.id' => $student_id])
                       ->matching('CourseMemberships', function ($q) {
                            return $q->where([ 'CourseMemberships.grade' => 'A']);
                       });

* Recommendation: use $studentId, not $student_id.

On Sun, Jul 26, 2015 at 9:06 PM, Zbigniew LedwoĊ„ <zledwon@gmail.com> wrote:
if I have an association exactly like in the CookBook here:

class StudentsTable extends Table  {      public function initialize(array $config)      {          $this->belongsToMany('Courses', [              'through' => 'CourseMemberships',          ]);      }  }    class CoursesTable extends Table  {      public function initialize(array $config)      {          $this->belongsToMany('Students', [              'through' => 'CourseMemberships',          ]);      }  }    class CoursesMembershipsTable extends Table  {      public function initialize(array $config)      {          $this->belongsTo('Students');          $this->belongsTo('Courses');      }  }
Student BelongsToMany Course  Course BelongsToMany Student
id | student_id | course_id | days_attended | grade
How do I find all Courses that given Student has Grade == "A"?
Would following code work fine?

$query = $this->Courses->find('all')
    ->contain(['Students', 'CourseMemberships'])
    ->where(['Students.id' => $student_id, 'CourseMemberships.grade' => 'A']);


--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.



--
Atenciosamente,

Rafael F. Queiroz

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: