【问题标题】:CakePHP 3: belongsToMany (through) and additional associationsCakePHP 3:belongsToMany(通过)和附加关联
【发布时间】:2017-07-18 22:14:33
【问题描述】:

我定义了以下关联:

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”表具有以下结构:

id | recipe_id | ingredient_id | unit_id | ...

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

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

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

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

【问题讨论】:

    标签: php cakephp cakephp-3.x


    【解决方案1】:

    这将无法使用contain(),至少不适用于belongsToMany 关联,因为为连接表动态创建的中间关联创建得太晚,以至于急切的加载程序无法识别它。

    您可以做的是手动为连接表显式创建其他即时生成的hasMany 关联,例如在RecipesTable 类上添加:

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

    然后您可以包含您的关联,例如:

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

    【讨论】:

    • 好的,是的。我已经考虑过了。如果不访问中间的“通过”表来获取数据,那就太好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多