6

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

我已经阅读了有关虚拟字段的信息,您可以使用它来组合如下字段:

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

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

4

1 回答 1

6

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

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

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

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

然后在用户控制器中:

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');
于 2012-06-18T14:55:03.117 回答