Tornseglare
Tornseglare

Reputation: 1177

Cakephp 3 model find fails with contain anonymous function

I get "An Internal Server Error Occurred" on this simple query:

$query = $this->find()
    ->contain(['CatLang' => function(Query $q) use($i18n){
      return $q->where(['CatLang.i18n' => $i18n]);
    }])
    ->where(['Categories.id' => $categoryId]);

$category = $query->first();

The tables look like this, simplified:

  categories
    id

  cat_lang
    category_id
    i18n

The models are named CategoriesTable and CatLangTable, both extending Table.

CatLangTable belongsTo Categories:

$this->belongsTo('Categories');

..and Categories hasMany CatLangs:

$this->hasMany('CatLang');

The query is run from a function in CategoriesTable. A working query in mysql would look like this:

SELECT * FROM categories AS c 
INNER JOIN cat_lang as cl ON cl.category_id=c.id
WHERE c.id=13
AND cl.i18n='sv'

This query would return the result set from one row in categories with id 13, joined with one row from cat_lang where i18n equals 'sv'. (category_id and i18n have a unique index.)

Can anyone please advice me, what am I doing wrong?

Using cakephp 3.5.17, php 7, and mysql 5.7.

Upvotes: 0

Views: 878

Answers (1)

Tornseglare
Tornseglare

Reputation: 1177

My bad. As ndm noted in the comments, I completely missed out to import the Query namespace.

use Cake\ORM\Query;

The error message was clear enough if I would have cared about reading it: :-)

App\Model\Table\CategoriesTable::App\Model\Table\{closure}() 
must be an instance of App\Model\Table\Query, 
instance of Cake\ORM\Query given

Hope it helps someone.

Upvotes: 3

Related Questions