Hi there,
I have a table “articles” with the following fields (id, parent_id, name, content)
Each article belongsTo ParentArticles and hasMany ChildArticles
The associations in the articles table:
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('articles');
$this->setPrimaryKey('id');
$this->setDisplayField('name');
//Behaviors
$this->addBehavior('Timestamp');
//Associations
$this->belongsTo('ParentArticles', [
'className' => 'Articles',
'foreignKey' => 'parent_id'
]);
$this->hasMany('ChildArticles', [
'className' => 'Articles',
'foreignKey' => 'parent_id'
]);
}
I have this data (in the right format of course) in the database:
[
{"id":"1","parent_id":null,"name":"Dummy article 1","summary":"Dummy article 1 summary","content":"Dummy article 1 content"},
{"id":"2","parent_id":"1","name":"Dummy article 2","summary":"Dummy article 2 summary","content":"Dummy article 2 content"},
{"id":"3","parent_id":"2","name":"Dummy article 3","summary":"Dummy article 3 summary","content":"Dummy article 3 content"}
]
When I do a find like this:
$article = $this->Articles->find()->select([
'id',
'parent_id',
'name',
'summary',
'content'
])->where([
'Articles.id'=>1
])->contain([
'ChildArticles'=>[
'fields'=>['id','parent_id','name','summary','content'],
],
])->enableHydration(false)->first();
It produces this:
Array
(
[id] => 1
[parent_id] =>
[name] => Dummy article 1
[summary] => Dummy article 1 summary
[content] => Dummy article 1 content
[child_articles] => Array
(
[0] => Array
(
[id] => 2
[parent_id] => 1
[name] => Dummy article 2
[summary] => Dummy article 2 summary
[content] => Dummy article 2 content
)
)
)
And when I do this:
$article = $this->Articles->find()->select([
'id',
'parent_id',
'name',
'summary',
'content'
])->where([
'Articles.id'=>1
])->contain([
'ChildArticles'=>[
'fields'=>['id','parent_id','name','summary','content'],
'ChildArticles'=>[
'fields'=>['id','parent_id','name','summary','content'],
],
],
])->enableHydration(false)->first();
I get this:
Array
(
[id] => 1
[parent_id] =>
[name] => Dummy article 1
[summary] => Dummy article 1 summary
[content] => Dummy article 1 content
[child_articles] => Array
(
)
)
Plus this error:
Undefined index: parent_id [ CORE\src\ORM\Association\Loader\SelectLoader.php , line 471 ]
But when the enableHydration(true) I no error but still no result for the child_articles.
The second find should find the article of ID 1 plus all the associated data but its failing. Not specifying the fields (or specifying like this Association.field) options in contain makes no difference to the outcome.
Am I doing something wrong somewhere or could this be a bug?