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.

图片转代码服务由CSDN问答提供 功能建议

我已经定义了以下关联:

  class  RecipesTable扩展了Table 
 {
 $ this-> belongsToMany('Ingredients',[
'到'=>'RecipesIngredients',
'externalKey'=>'recipe_id',
'targetForeignKey'=  >'ingredient_id',
]); 
 
class IngredientsTable扩展表
 {
 $ this-> belongsToMany('Recipes',[
'到'=>'RecipesIngredients',
'  foreignKey'=>'ingredient_id',
'targetForeignKey'=>'recipe_id',
]); 
 
class RecipesIngredientsTable扩展表
 {
 $ this-> belongsTo('Recipes');  
 $ this-> belongsTo('Ingredients'); 
 $ this-> belongsTo('Units'); 
   
 
 

表'RecipesIngredients' 具有以下结构:

  id |  recipe_id |  ingredient_id |  unit_id |  ... 
   
 
 

现在我发出如下所示的请求以获取食谱和相关成分。 但没有单位。

  $ data = $ this-> Recipe-> find('all')
  - > where('Recipe.id  '=> 55)
  - >包含(['成分',...])
  - >所有(); 
   
 
 

我的 问题是:如何在 $ this-> Recipe 的调用中获取相关“单位”的数据?

我尝试了不同的包含类似< code> - &gt; contains(['Ingredient'=&gt; ['Unit'],...])(等等),但这不起作用。 CakePHP只返回关联的 ingredients 和'through'连接表的内容,而不链接到关联的 units 。 或者给出错误关联的错误。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题