CakePHP 3:belongsToMany(通过)和附加关联

CakePHP 3: belongsToMany (through) and additional 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');

table 'RecipesIngredients' 具有以下结构:

id | recipe_id | ingredient_id | unit_id | ...

现在我提出如下请求以获取食谱和相关配料。但是没有单位。

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

我的问题是:如何在 $this->Recipe 的调用中获取关联的 'Units' 的数据?

我尝试了不同的包含,例如 ->contain(['Ingredient' => ['Unit'], ...])(等等),但这不起作用。 CakePHP 只是 returns 关联 ingredients 和 'through' 的内容加入 table 而没有链接到关联 units。或者给出缺少关联的错误。

这将无法使用 contain(),至少不适用于 belongsToMany 关联,因为正在为连接 table 创建即时创建的中间关联为时已晚,急切的加载程序无法识别它。

你可以做的是明确地为加入 table 手动创建另外即时生成的 hasMany 关联,例如在 RecipesTable class 添加:

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

然后你可以像这样包含你的联想:

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