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

Build custom input field list with display field from associated model in cakephp 3

我有三个 table campaign_social_accountssocial_accountssocial_networks

SocialNetworks 包含用户可以连接到的网络,列为

+-----+--------+
| id  | title  |
+-----+--------+

SocialAccounts 用户连接的所有帐户的列为

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

CampaignSocialAccountsCampaigns 有关联并向该活动添加了社交帐户

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

CampaignSocialAccountsadd() 中,我希望用户从 SocialAccounts select 为此,这就是我在控制器

中所做的
$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)

其中 FacebookYoutubeSocialNetworks table 的标题,(112233....)SocialAccountsuser_key 和生成的选项的值将是 SocialAccounts

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

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

Edit 2: My Try

在控制器动作中

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

SocialAccount.php实体

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

还是没效果

在您的 SocialAccounts 实体中,您可以定义虚拟 属性

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

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

在你的控制器中

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