使用cakephp 3中关联模型的显示字段构建自定义输入字段列表

时间:2017-06-29 06:00:00

标签: cakephp cakephp-3.4

我有三个表campaign_social_accountssocial_accountssocial_networks

SocialNetworks包含用户可以通过

列连接到的网络
+-----+--------+
| id  | title  |
+-----+--------+

SocialAccounts将所有帐户用户连接到列

+----+---------+-------------------+--------------+----------+
| id | user_id | social_network_id | access_token | user_key |
+----+---------+-------------------+--------------+----------+

CampaignSocialAccounts已与Campaigns关联,并为该广告系列添加了社交帐户

+-----+-------------+-------------------+
| id  | campaign_id | social_account_id |
+-----+-------------+-------------------+

add()的{​​{1}}中我希望用户从CampaignSocialAccounts中选择,这就是我在控制器中所做的事情

SocialAccounts

$socialAccounts = $this->CampaignSocialAccounts->SocialAccounts->find('list', [ 'conditions' => [ 'user_id' => $this->Auth->user('id') ] ]);

add.ctp

问题

这会在列表中显示echo $this->Form->control('social_account_id', ['options' => $socialAccounts]); ,因为该字段中没有其他列可以设置为id

另外,我想显示类似

的列表
displayField()

其中Facebook(112233445566) Youtube(2233112233) Facebook来自Youtube表的标题,而SocialNetworks来自(112233....)的{​​{1}},并且生成的选项的值将为user_keySocialAccounts

id
SocialAccounts

是否有可能,如果是的话,最好和最简单的方法是什么。

  

编辑2:我的尝试

在控制器操作中

<option value="1<id from social_accounts>">Facebook(112233445566)</option>
<option value="2<id from social_accounts>">Youtube(2233112233)</option>

SocialAccount.php实体

$socialAccounts = $this->CampaignSocialAccounts->SocialAccounts
    ->find('list', ['valueKey' => 'social_account_title'])
    ->contain(['SocialNetworks'])
    ->where(['user_id' => $this->Auth->user('id')]);

仍然没效果

1 个答案:

答案 0 :(得分:1)

您可以在SocialAccounts实体中

定义虚拟财产

public function _getFullName()
{
    if(isset($this->social_network))
        return $this->social_network->name.' ('.$this->user_key.')';
    return $this->id;
}

然后tu可以在find()调用中使用您的新虚拟属性

控制器中的

$socialAccounts = $this->CampaignSocialAccounts->SocialAccounts
    ->find('list', ['valueField' => 'full_name'])
    ->contain(['SocialNetworks'])
    ->where(['user_id' => $this->Auth->user('id')]);
相关问题