Yii2如何使用带有自定义别名和动态别名的数据提供程序



在yii2中,我必须使用带有用户定义的动态别名的SQL。

因为它是动态的所以不可能在模型中添加公共属性

所以下面的代码不能使用下面的SQL:

SELECT `item_id`         AS `Item Id`,
`on_hand`         AS `On Hand`,
`initial_on_hand` AS `Amount Produced`,
`best_by_date`    AS `Best By`,
`item_name`               AS `Item Name`
FROM   `stock` 

下面是yii2代码:

$dataProvider = new ActiveDataProvider([
'query' => $query,
]);

那么我可以使用yii2网格分页和控件的可能解决方案是什么?

使用此解决方案

$query = (new Query()) 
->select(
'stock.item_id as Item Id,
stock.on_hand as On Han,
stock.intial_on_hand as Amount Produced,
stock.best_By_date as Best By ,
stock.item_name as Item Name
)
->from('notifications as n') ->all()

------------------------------------------------------------------------

如果你的目的是获取标签,你可以简单地在模型库中创建一个名为attributeLabels()的方法。

public function attributeLabels()
{
return [
'item_id' => 'Item Id',
'on_hand' => 'On Hand',
'initial_on_hand' => 'Amount Produced`,
'decaissement_id' => 'Decaissement ID',
'best_by_date' => 'Approved By',
'item_name' => 'Item Name',
];
}

如果你绝对坚持在SQL查询中使用用户输入作为别名,你可以使用yiidataSqlDataProvider而不是yiidataActiveDataProvider

我仍然认为这样做是非常糟糕的主意,因为可能的SQL注入。在SQL查询中不能使用参数作为别名。这意味着你允许用户直接修改你的SQL查询。

如果你想要动态标签,你可以这样做。让我们假设您在DB中有一些dynamic_label标签,其中存储了后端设置的标签。这个表可以像这样:

标签th>项ID
$query = StockModel::find();
$query->select([
'stock.item_id as Item Id',
'stock.on_hand as On Han',
'stock.intial_on_hand as Amount Produced',
'stock.best_By_date as Best By',
'stock.item_name as Item Name'
]);
$dataProvider = new ActiveDataProvider(['query' => $query]);

最新更新