【问题标题】:Cakephp virtual field if this column empty use this column如果此列为空,Cakephp 虚拟字段使用此列
【发布时间】:2013-12-21 09:59:37
【问题描述】:

我有一个名为“Contacts”的表,我想创建一个名为 customer 的虚拟字段。

Contacts 有列,名为 first_name、last_name、company。

我通过连接所有三个来创建虚拟字段

public $virtualFields = array(
'customer' => "CONCAT(Contact.first_name, ' ', Contact.last_name, ' ', Contact.company)"        
);

但是我怎样才能创建它,所以它只显示公司,但如果它是 null 或空字符串,它将显示名字和姓氏

【问题讨论】:

    标签: mysql sql database cakephp cakephp-2.0


    【解决方案1】:

    您可以尝试将 SQL IF 语句放入其中:

    public $virtualFields = array(
    'customer' => "IF(Contact.company IS NULL OR Contact.company = '', CONCAT(Contact.first_name, ' ', Contact.last_name, ' ', Contact.company), Contact.company)"
    );
    

    is null or is empty 而言,您的数据库是否没有一致的空值?如果没有,它应该并且你应该解决它......

    【讨论】:

    • 对不起,我的数据库设置为默认值无。我应该如何处理这个?我应该在公司 IS NULL 中输入什么?
    • 上面的 if 语句是说“如果公司为空,则将名称连接在一起,否则使用公司”。如果您的 db 默认值为 none,则应将其设置为可空的默认 null 以保持一致性
    • 已更新我的答案以包含空白案例。让我知道它是否有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-23
    相关资源
    最近更新 更多