doucheng9058 2013-10-18 13:21
浏览 58
已采纳

Yii Active Record COALESCE不显示结果

I have the following query:

$result = Table1::model()->findAll(array(
    'with' => array(
                'table2' => array(
                    'joinType' => 'LEFT JOIN',
                    'on' => 'pk = fk AND fk=1'
                )
            ),
    'select' => array('name',
                      'COALESCE(table2.price, t.standardprice) AS price',
                      'COALESCE(table2.period, t.period) AS period')
    )
);

My goal is to pick table2's fields if those are filled in, but if these are empty / no rows found the original table's fields should be displayed.

However, my output isn't as expected. The price field isn't displayed at all in my result's attributes, and the period field is either table2's value or empty.

EDIT: Perhaps my SQL is wrong somewhere. Using this SQL gives me the wanted results:

SELECT name, COALESCE(tb1.price, tb2.standardprice) as price, COALESCE(tb1.period, tb2.period) as period
FROM table1 as tb1
LEFT JOIN table2 as tb2
ON (tb1.pk= tb2.fk) AND fk=1;

Yet I don't see any difference with my current code.

EDIT2: Table structures:

Table1 (original table)

pk            (int 11) - Primary key, auto increment
name          (varchar 255)
standardprice (decimal 11,2)
period        (varchar 255)
fkLanguage    //not relevant
photo         //not relevant
description   //not relevant
link          //not relevant

Table2

ID      (int 11) - Primary key, auto increment
fk      (int 11) - Foreign key, which links to pk of table1
period  (varchar 255)
price   (decimal 11,2)
fkType  //not relevant
amount  //not relevant

Clarification: The fk=1 is indeed a JOIN condition. If the fk isn't 1 then I don't want those rows to join, but take the values from table1 instead.

  • 写回答

2条回答 默认 最新

  • doushouhe7072 2013-10-21 13:52
    关注

    You need to add column price for parsing not existing column in schema.
    Try to modify model Table1 ()

    • add public $price;
    • override method attributeNames to following:
    public function attributeNames()
      {
          $colums = parent::attributeNames();
          $colums[] = 'price';
          return $colums;
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码