我試圖在ActiveDataProvider添加新的領域或平衡計算的列(transactionSearch.php模型)查詢Yii的2 ActiveDataProvider:額外的字段或做對數據提供程序
時候當我做這個平衡計算的列SQL到phpmyAdmin,它完美的作品。我從stackoverflow研究中得到了這段代碼。由於
SET @bal = 0;
SELECT t.* , @bal:[email protected] AS balance
FROM(
SELECT *
FROM transaction
WHERE user_id = 1
) t
但是,當我試圖融入transactionSearch.php模型
$query = Transaction::find();
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
這是我做過什麼
// since I need to prepare query before starting the ActiveDataProvider query, I did this
$connectionz = Yii::$app->getDb();
$query = $connectionz->createCommand("SET @bal = 0");
$query = $query->query();
// then I run the usual query
$query = Transaction::findBySql('
SELECT t.* , @bal:[email protected] AS balance
FROM(
SELECT *
FROM transaction
WHERE user_id = 1
) t ')->all();
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
在attributeLabel & 規則除了加入平衡,我也加了Transaction.php模型的setter和getter,但是我一個m 不是肯定是對的還是我缺添加任何規則?
public function setBalance($balance)
{
$this->balance = (float) $balance;
}
public function getBalance()
{
return '';
}
但它出來錯誤Call to a member function andFilterWhere() on array
任何建議,將好心讚賞
兩者似乎都不起作用........................................ .. 1)出來錯誤** preg_match()期望參數2是字符串,給定的對象** ......................... .................................................. .............. 2)出來也出錯** SQLSTATE [42S22]:未找到列:1054未知列'@bal:[email protected]'in'field list ' 正在執行的SQL是:SELECT'transaction'。*,'@bal:= t'.'amount + @ bal'AS'balance' FROM'transaction' WHERE'user_id' = 1 ORDER BY'date' LIMIT 20 * * – liongrobert
嘗試使用http://www.yiiframework.com/doc-2.0/yii-db-expression。html - > select([transaction。*,'balance'=> $ expression]) – zakrzu
哇! 。感謝@ zakrzu。 – liongrobert