jagguy
jagguy

Reputation: 183

cant display rows from belongsToMany

I cant display any rows from a belongsToMany relationship (tutors have subjects). I use the exact same code on another table but for some reason this code gives an error which says the colum doesnt exist when it does.

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Subjects.subject_id' in 'on clause'

$tid = 12;
$sub = $this->Subjects->find('list')->hydrate(true);

$sub->matching('Tutors', function ($q) use ($tid) { 
    return $q->where(['Tutors.id' =>$tid]);
});   

Model in tutors

$this->belongsToMany('Subjects', [
   'foreignKey' => 'tutor_id',
   'targetForeignKey' => 'subject_id',
   'joinTable' => 'tutors_subjects'
]);

Upvotes: 1

Views: 66

Answers (1)

Jacek B Budzynski
Jacek B Budzynski

Reputation: 1413

Try rename your table tutors_subjects as subjects_tutors

Join tables, used in BelongsToMany relationships between models, should be named after the model tables they will join, arranged in alphabetical order (articles_tags rather than tags_articles)

More Info Model and Database Conventions

Upvotes: 3

Related Questions