我有以下查询:
$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')
)
);
我的目标是选择填写表2的字段,但如果这些字段为空/找不到行,则应显示原始表格的字段。
但是,我的输出并不像预期的那样。我的结果的属性中根本没有显示price
字段,period
字段是table2的值或为空。
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;
然而,我发现我目前的代码没有任何区别。
EDIT2:表结构:
表1 (原始表格)
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
表2
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
澄清:fk=1
确实是一个加入条件。如果fk不是1,那么我不希望这些行加入,而是从table1中获取值。
答案 0 :(得分:1)
您需要添加列price
来解析模式中不存在的列
尝试修改模型Table1()
public $price;
public function attributeNames() { $colums = parent::attributeNames(); $colums[] = 'price'; return $colums; }
答案 1 :(得分:0)
我认为你应该这样做:
$result = Tablename::model()->findAll(array(
'with' => array(
'tabel2' => array(
'joinType' => 'LEFT JOIN',
'on' => 'pk = fk'
)
),
'select' => array('name',
'COALESCE(tabel2.price, t.standardprice) AS price',
'COALESCE(tabel2.period, t.period) AS period'),
'condition'=> ' fk = 1 '
));
因为fk = 1不是on语句的一部分;这只是一个条件。我认为这对你有所帮助。