gpt4 book ai didi

cakephp - 使用相关模型中的字段作为 CakePHP 中的显示字段

转载 作者:行者123 更新时间:2023-12-04 15:02:02 24 4
gpt4 key购买 nike

我有一个不包含任何标题的模型。所有有趣的信息都在一个相关的模型中。

我已经读过关于 virtualfields 的文章,你可以用它组合这样的字段:

public $virtualFields = array("full_name"=>"CONCAT(event_id, ' ' ,begin)");
public $displayField = 'full_name';

但这给了我一个简单的 id 和一个日期。我需要该 id 是另一个模型的名称。

最佳答案

这听起来真的是 Set::combine() 的工作.你的显示字段不应该引用不同的模型,因为它并不总是保证被加入。所以如果某个地方的调用没有引入数据,它会抛出一个错误。

相反,使用 Set::combine()你可以用你想要的任何东西创建一个键值数组。虽然这不那么“神奇”,但它会减少出错的可能性。

对于 UsersController 示例,假设您有 hasOne 个人资料,并希望用户使用自动填充的下拉列表(即使用 FormHelper)选择用户,该下拉列表会显示用户个人资料中的全名。我们将使用 Containable引入配置文件数据。

class AppModel extends Model {
$actsAs = array(
'Containable'
);
}

然后在用户 Controller 中:
function choose($id = null) {
// regular view code here
$users = $this->User->find('all', array(
'contain' => array(
'Profile'
)
));
// create a key-value that the FormHelper recognizes
$users = Set::combine($users , '{n}.User.id', '{n}.Profile.full_name');
}

你会注意到 full_name现在在 Profile 模型上,因为它使用该模型中的字段。 combine 方法创建一个数组,如
array(
1 => 'skerit',
2 => 'jeremy harris'
);

当您使用 FormHelper 创建下拉列表时将自动使用
echo $this->Form->input('user_id');

关于cakephp - 使用相关模型中的字段作为 CakePHP 中的显示字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11081259/

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