我在寻找以前的答案,但我发现的是与更老的cakephp版本相关
i was looking for a previous answer, but the ones i've found are related to older cakephp versions
我有两个表,杂志 '在这里有一个关系'issues'BelongsTo'magazines',这是什么IssuesTable看起来像:
i have two tables, 'magazines' and 'issues' where there is a relation 'issues' BelongsTo 'magazines', this is what IssuesTable looks like:
public function initialize(array $config){ $this->belongsTo('Magazines', [ 'foreignKey' => 'id' ]); }表杂志有两个字段:magazines.id和magazines.name
table magazines has two fields, magazines.id and magazines.name
表问题有两个字段,issues.id,issues.magazine_id其中issues.magazine_id是外键
table issues has two fields, issues.id, issues.magazine_id where issues.magazine_id is the foreign key
填充使用magazine.name值在问题视图中选择输入并保存issues.magazine_id,我已将控制器设置为
to populate a select input in the issues view with the magazine.name values and save the issues.magazine_id, i've set the controller like this
$this->set('magazines', $this->Issue->Magazine->find('list'));然后我已添加以下代码到问题视图add.cpt
then i've added the following code to the issue view add.cpt
<?php echo $this->Form->input('name', [ 'type' => 'select', 'multiple' => false, 'options' => $magazines, 'empty' => true]); ?>但我得到输入选择与issues.magazine_id作为值,而不是magazines.name
but i get the input select with the issues.magazine_id as values instead of magazines.name
感谢您的帮助和意见
推荐答案$ c> find('list'),因为这将返回主键和显示字段: -
You want to use find('list') as this will return the primary key and display field:-
$this->set( 'magazines', $this->Issues->Magazines->find('list') );然后在您的表单中,您需要输入名称 magazine_id 如果您要为关联设置外键: -
Then in your form you need the input name to be magazine_id if you're wanting to set the foreign key for the association:-
echo $this->Form->input( 'magazine_id', [ 'type' => 'select', 'multiple' => false, 'options' => $magazines, 'empty' => true ] );请参阅
See the docs for more info.
更新
如果您遇到 find('list')的问题,可能是因为您的模型的 displayField 无法正确设置。 Cake通常决定初始化时模型的 displayField 。如果这不工作,或者你想要一个不同的字段,你可以在模型的 initialize()方法中手动设置。 例如: -
If you're experiencing issues with find('list') it is perhaps because your model's displayField is not getting set correctly. Cake normally determines the displayField for the model on initialisation. If this isn't working, or you want a different field you can set this manually in the model's initialize() method. E.g.:-
class MagazinesTable extends Table { public function initialize(array $config) { $this->displayField('name'); } }更改'name'到相应的字段。
或者,您可以选择Cake将使用 find list')(当你想要覆盖默认的 displayField 时,这是特别有用的)。 : -
Alternatively, you can choose which field Cake will use for the values returned by find('list') (this is particularly useful when you want to override the default displayField). E.g.:-
$this->Issues->Magazines->find('list', [ 'keyField' => 'id', 'valueField' => 'name' ]);更多推荐
cakephp 3.0如何填充一个选择字段值,而不是id
发布评论