CakePHP的3:belongsToMany(通过)和
问题描述:
我已经定义以下关联附加关联: CakePHP的3:belongsToMany(通过)和
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
。或者给出缺失关联的错误。
答
这不会使用contain()
,至少不会与belongsToMany
关联,因为正在创建的连接表的即时创建的中间关联创建得太晚而无法让渴望加载器识别它。
你可以做的是明确创建,否则上即时生成hasMany
协会连接表手动,例如在RecipesTable
类添加:
$this->hasMany('RecipesIngredients', [
'foreignKey' => 'recipe_id'
]);
然后你就可以包含类似的相关项目:
->contain(['RecipesIngredients' => ['Ingredients', 'Units']])
好的。我已经想过这个。如果不访问两者之间的“通过”表而获取数据本来就太棒了。 – mixable