【问题标题】:can't save data, when create new data by same category按相同类别创建新数据时无法保存数据
【发布时间】:2019-03-27 11:30:49
【问题描述】:

型号

错误: “数组到字符串的转换(SQL:更新spent_times设置updated_at=2018-10-23 09:16:43,spent_time=16,percentage=70,task_category=测试其中id= 1) ◀"

public static function findOrCreate($plan_id, $data)
{
    $fromDate = Carbon::now()->subDay()->startOfWeek();
    $nowDate = Carbon::now()->today();

    $spent_time = static::where('plan_id', $plan_id)->first();

    if (is_null($spent_time)) {
        return static::create($data);
    }else{
        $new_spent_time = SpentTime::first();
        $task_category = $new_spent_time->task_category;
        $new_spent_time->spent_time = $new_spent_time::where('task_category',$task_category)
                                    ->sum('daily_spent_time', $new_spent_time->daily_spent_time , $fromDate);
        $new_spent_time['spent_time'] = $new_spent_time->spent_time + $spent_time->daily_spent_time;

        $new_spent_time->percentage = $new_spent_time::where('task_category',$task_category)
                                    ->sum('daily_percentage', $new_spent_time->daily_percentage, $fromDate);
        $new_spent_time['percentage'] = $new_spent_time->percentage  + $spent_time->daily_percentage;
        $new_spent_time->save();
        return $spent_time->update($data);
    }
}

为什么只有第一个 ID?

【问题讨论】:

  • 第一个 ID 是什么?请澄清你在说什么。至于错误,这意味着您正在尝试在字符串中打印数组,这不是合乎逻辑的事情。但我们不知道您的哪些变量是数组。
  • `$new_spent_time = SpentTime::first();'表中的 id_spend_times
  • 它只是第一个 ID,因为您使用 SpentTime::first(); 获取它并且它正在更新
  • @LeenaPatel 会影响保存吗?
  • 是的,当你已经在使用update()时,你不需要使用save()

标签: php laravel-5 sum laravel-query-builder laravel-5.7


【解决方案1】:

更新答案

型号

public static function findOrCreate($plan_id, $data)
{
    $spent_time = static::where('plan_id', $plan_id)->first();
    $task_category = $spent_time->task_category;

    if (is_null($spent_time)) {
        return static::create($data);
    }else{
        $spent_time['spent_time'] = $spent_time->spent_time + $spent_time->daily_spent_time;

        $spent_time['percentage'] = $spent_time->percentage  + $spent_time->daily_percentage;
        return $spent_time->update($data);
    }
}

【讨论】:

    猜你喜欢
    • 2019-03-22
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多