gpt4 book ai didi

mysql - Yii2 更新查询产生的记录

转载 作者:行者123 更新时间:2023-11-29 02:13:35 24 4
gpt4 key购买 nike

我需要使用从 Controller 传递的一些变量更新选择查询产生的记录的 month_no 字段,但每个字段都写入相同的值。

这些是变量:

    $id_calc = 27
$from_y = "2013-05-01"
$to_y = "2015-11-31"

表格结果:

   id   id_paid   year_ref     month_no
1 26 2012 12
2 26 2013 12
4 27 2013 12 (should be 8)
5 27 2014 12
6 27 2015 12 (should be 11)

这是模型:

 public function CorrectTable($id_calc, $from_y, $to_y)
{
$connection = Yii::$app->db;
$query = "SELECT * FROM my_table where id_paid='$id_calc'";
$data = $connection->createCommand($query)->queryAll();
// calculate no. of month first and last year
$month_no_begin = (13 - date("m",strtotime($from_y)));
$month_no_end = (date("m",strtotime($to_y)));
//
foreach($data as $row)
{
$id = $row['id'];
// calculate number of month per year
if ($row['year_ref'] = date("Y",strtotime($from_y)))
{
$month_no = $month_no_begin;
} elseif ($row['year_ref'] = date("Y",strtotime($to_y)))
{
$month_no = $month_no_end;
} else
{
$month_no = 12;
}
Yii::$app->db->createCommand()
->update('my_table', ['month_no' => $month_no], ['id' => $id])
->execute();
}

我尝试将上述代码放入 Controller 中,结果相同。

最佳答案

我曾经犯过一个粗心的错误。您应该在 if 语句中使用 ===== 来测试相等条件,而不是 =

public function CorrectTable($id_calc, $from_y, $to_y)
{
$connection = Yii::$app->db;
$query = "SELECT * FROM my_table where id_paid='$id_calc'";
$data = $connection->createCommand($query)->queryAll();
// calculate no. of month first and last year
$month_no_begin = (13 - date("m",strtotime($from_y)));
$month_no_end = (date("m",strtotime($to_y)));
//
foreach($data as $row)
{
$id = $row['id'];

// use `==` instead of `=`
if ($row['year_ref'] == date("Y",strtotime($from_y)))
{
$month_no = $month_no_begin;
}

// use `==` instead of `=`
elseif ($row['year_ref'] == date("Y",strtotime($to_y)))
{
$month_no = $month_no_end;
}
else
{
$month_no = 12;
}

Yii::$app->db->createCommand()
->update('my_table', ['month_no' => $month_no], ['id' => $id])
->execute();
}
}

关于mysql - Yii2 更新查询产生的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44980527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com