CakePHP 3:beforeToMany(通过)和其他关联 [英] CakePHP 3: belongsToMany (through) and additional associations
问题描述
我定义了以下关联:
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');
表 RecipesIngredients具有以下结构:
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();
我的问题是:如何在<的调用中获取关联的单位的数据code> $ this->食谱?
我尝试了类似-> contain( ['Ingredient'=> ['Unit'],...])
(依此类推),但这不起作用。 CakePHP只是返回关联的成分
和'through'连接表的内容,而没有链接到关联的单位
。或给出缺少关联的错误。
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.
推荐答案
使用 contain()无效code>,至少不与
belongsToMany
关联,因为为连接表动态创建的中间关联中间创建对于渴望的加载者来说为时已晚认识到它。
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.
您可以做的是显式创建否则将动态生成的 hasMany
关联手动连接表,例如在 RecipesTable
类上添加:
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']])
这篇关于CakePHP 3:beforeToMany(通过)和其他关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!