gpt4 book ai didi

php - CakePHP 3 - 关联 BelongsToMany 和 hasMany - 通过选择限制列

转载 作者:行者123 更新时间:2023-11-29 07:12:01 28 4
gpt4 key购买 nike

美好的一天!我对 CakePHP 3 有一个小问题。我有这样的关联:

       $this->belongsToMany('AdminUserGroup',[
'classname' => 'AdminUserGroup',
'foreignKey' => 'admin_user_id',
'targetForeignKey' => 'group_id',
'joinTable' => 'AdminUsersGroups'
]);

我正在使用以下代码返回记录:

public function getAll()
{
$ble = $this->find()
->contain(['AdminUserGroup' ]);
return $ble;
}

直到它起作用,但是当我想选择指定的字段时我遇到了问题。当我添加选择方法时,我看不到包含的表中的列:

public function getAll()
{
$ble = $this->find()->select(['id', 'name', 'surname'])
->contain(['AdminUserGroup']);
return $ble;
}

所以我添加了回调查询:

public function getAll()
{
$ble = $this->find()->select(['id, name, surname'])
->contain(['AdminUserGroup' => function ($q) { return $q->select(['group_name']);}]);
return $ble;
}

但是还是不行。我只能看到主表中的字段。包含表的字段不会出现。

{
"id": "8",
"name": "Ola",
"lastname": "BleBle",
"admin_user_group": []
},

如何修复它?

最佳答案

manual包括以下评论:

When you limit the fields that are fetched from an association, you must ensure that the foreign key columns are selected. Failing to select foreign key fields will cause associated data to not be present in the final result.

If you have limited the fields you are loading with select() but also want to load fields off of contained associations, you can pass the association object to select().

Alternatively, if you have multiple associations, you can use autoFields().

那里有一些有用的例子。所以:

$ble = $this->find()
->select(['id', 'name', 'surname'])
->contain(['AdminUserGroup' ])
->autoFields(true);

或者如果您使用的是 3.1 或更高版本:

$ble = $this->find()
->select(['id', 'name', 'surname'])
->select($this->AdminUserGroup);

从示例来看,第二个版本中可能不需要 contain 调用,因此我将其省略。

关于php - CakePHP 3 - 关联 BelongsToMany 和 hasMany - 通过选择限制列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39324854/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com