CakePHP 3: belongsToMany (through) and additional associations

拟墨画扇 提交于 2019-12-24 08:38:49

问题


I have defined the following associations:

class RecipesTable extends Table
{
  $this->belongsToMany('Ingredients', [
    'through' => 'RecipesIngredients',
    'foreignKey' => 'recipe_id',
    'targetForeignKey' => 'ingredient_id',
  ]);

class IngredientsTable extends Table
{
  $this->belongsToMany('Recipes', [
    'through' => 'RecipesIngredients',
    'foreignKey' => 'ingredient_id',
    'targetForeignKey' => 'recipe_id',
  ]);

class RecipesIngredientsTable extends Table
{
  $this->belongsTo('Recipes');
  $this->belongsTo('Ingredients');
  $this->belongsTo('Units');

The table 'RecipesIngredients' has the following structure:

id | recipe_id | ingredient_id | unit_id | ...

Now I make a request like the one below to get Recipes and the associated Ingredients. But without the Units.

$data = $this->Recipe->find('all')
    ->where('Recipe.id' => 55)
    ->contain(['Ingredient', ...])
    ->all();

My question is: how do I get the data of the associated 'Units' in a call of $this->Recipe?

I tried different contains like ->contain(['Ingredient' => ['Unit'], ...]) (and so on) but this doesn't work. CakePHP just returns the associated ingredients and the contents of the 'through' join table without linking to the associated units. Or gives an error of missing associations.


回答1:


That won't work using contain(), at least not with a belongsToMany association, as the on-the-fly created intermediate association for the join table is being created too late for the eager loader to recognize it.

What you can do is explicitly create the otherwise on-the-fly generated hasMany association for the join table manually, eg on the RecipesTable class add:

$this->hasMany('RecipesIngredients', [
    'foreignKey' => 'recipe_id'
]);

Then you can contain your associations like:

->contain(['RecipesIngredients' => ['Ingredients', 'Units']])


来源:https://stackoverflow.com/questions/45178005/cakephp-3-belongstomany-through-and-additional-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!