By default, a hasMany
association will be done with a second query, not a join. Options for you include:
Flip the query so you’re getting cities and their matching countries. Cities should be a belongsTo
relation to Countries, which would do a join.
$results = $this->Countries->Cities->find()
->contain(['Countries'])
->where(['Countries.id' => 19])
->where(['Cities.name LIKE' => $name2 . '%'])
->limit(10);
Put the condition on the containment:
$results = $this->Countries->find()
->contain(['Cities' => [
'queryBuilder' => function(\Cake\ORM\Query $query) use ($name2) {
return $query->where(['Cities.name LIKE' => $name2 . '%'])
->limit(10);
}
]])
->where(['id' => 19]);
Force the join (I don’t generally do this, so the syntax might not be quite right):
$results = $this->Countries->find()
->leftJoinWith('Cities')
->contain(['Cities'])
->where(['Countries.id' => 19])
->where(['Cities.name LIKE' => $name2 . '%'])
->limit(10);
Note that each of these choices has some impact on what the resulting data structure will look like. I’d probably go with the first one, as that best resembles what you actually want: you want to find matching cities.