CakePHP 4: Problem with hasMany association and "contain" query

With CakePHP 4.0.8 I’m trying to create a query on 2 tables with an hasMany association:

$result = $this->Articles->find()
->contain(‘Comments’)
->all();

I’m getting the following error:

Unable to load Comments association. Ensure foreign key in Articles is selected.
(From: CORE/src/ORM/EagerLoader.php:662)

The same query with CakePHP 3.8.12 works fine

With CakePHP 4.0.8 the following query also works as expected:

$result = $this->Articles->get($id, [‘contain’ => ‘Comments’]);

The Article model has:

$this->hasMany('Comments', [
  'foreignKey' => 'article_id',
]);

The Comments model has:

$this->belongsTo('Articles', [
 'foreignKey' => 'article_id',
]);

Am I doing something wrong, or is this a bug in CakePHP 4.0.8?

1 Like

Just to be sure, you said “The Article model”, but it should be called “Articles”. Just a typo when you were writing this, or is your model incorrectly named “ArticleTable”?

Sorry, just a typo when writing this, the file is called “src/Model/ArticlesTable.php” and the Comments file is called “src/Model/CommentsTable.php”

1 Like

@Txj I have got problem like this, how do you fix this?

I had a same problem with hasMany association.
Solved it by this topic.
https://stackoverflow.com/questions/37323454/retrieve-related-data-hasmany-in-cakephp-3
Do not forget select foreign key column. :smiley: