dousao6313 2017-07-18 22:14
浏览 114
已采纳

CakePHP 3:belongsToMany(通过)和其他关联

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条回答 默认 最新

  • doufu3718 2017-07-20 18:49
    关注

    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']])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?