【问题标题】:Call to undefined method stdClass::save()调用未定义的方法 stdClass::save()
【发布时间】:2017-04-24 10:00:12
【问题描述】:

我正在尝试保存到数据库中,但我不断收到此错误

调用未定义的方法 stdClass::save()

我的控制器

 $c = DB::table('subject_user')->where('user_id', $value)->first();

 $c->auth_teacher = '1';

 $c->save();

【问题讨论】:

  • 您是否为 subject_user 表创建了模型? DB::table 方法不会返回具有保存方法的对象。
  • 不,我不这样做,因为那只是一个数据透视表,我将直接进入它
  • 除非你有一个独特的场景,否则我会尝试使用模型来做到这一点。看起来您对多对多关系具有枢轴值。以下堆栈线程是否对您有帮助。 stackoverflow.com/a/21942374/3750476。您的代码可能如下所示。 $user->subjects()->updateExistingPivot($subject->id, array('auth_teacher' => 1), false);

标签: php laravel laravel-5 eloquent laravel-5.2


【解决方案1】:

DB::table('subject_user')->where('user_id', $value)->update(['auth_teacher' => 1]);

我已经成功了。

【讨论】:

    【解决方案2】:

    试试这个方法

    我还没有尝试使用where 条件的save 方法。希望这种方法可以解决您的问题。

     DB::table('subject_user')->where('user_id', $value)->update(['auth_teacher' => 1]);
    

    【讨论】:

      【解决方案3】:

      我刚刚遇到了同样的问题,并想出了真正的 Laravel 答案。

      您在此处接受的答案 (https://stackoverflow.com/a/41051946/470749) 并不遵循最真实的 Laravel 方式。

      当我重新阅读 https://laravel.com/docs/5.4/eloquent#retrieving-models 的文档时,我注意到 ->save() 只有当我检索对象的方式是通过如下模型时才有效:

      $flights = App\Flight::where('active', 1)
                 ->orderBy('name', 'desc')
                 ->take(10)
                 ->get();
      

      没有必要在任何地方使用DB::table(),而且使用它似乎不是推荐的方式。

      因此,您可以将DB::table('subject_user')->where 更改为App\Subject_user::where(或任何适合您的)。

      【讨论】:

      • 这是更合适的答案。
      • 您似乎无法对 Eloquent 模型使用悲观锁。如果您需要防止竞争条件 DB::table() 是必须的。
      • 这对我也有帮助:stackoverflow.com/a/29166530/470749
      【解决方案4】:

      您可以在此处阅读,有两种保存/更新记录的方法。在您的情况下,您需要执行以下操作:https://laravel.com/docs/6.x/queries#updates

      $affected = DB::table('users')
                    ->where('id', 1)
                    ->update(['votes' => 1]); 
      

      【讨论】:

        【解决方案5】:

        在某些情况下,Laravel Controller 不接受 find 方法。也许你已经在你的控制器上试过了。

        解决方案-1)
        尝试在模型中使用 find 方法

        解决方案-2)
        尝试使用 Controller 中的 Where 子句 而不是 find。

        【讨论】:

          【解决方案6】:

          如果您开始使用 DB:: 而不是 Model:: 因为您需要动态表名调用,则可以使用动态接口调用来代替,但我想知道这是否是一个好习惯,任何愿意解释的人是否以下是错误的(因为它工作正常):

          $model = 'User'; //Use the name of the model, not the table name
          $interface_model = '\App\Models\\' . $model; //Needed to avoid the manual import of each model
          $entry = $interface_model::where('id', $id)->first();
          //$entry now support save()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-11-20
            • 1970-01-01
            • 1970-01-01
            • 2015-06-10
            • 2012-04-02
            • 2019-10-20
            • 2015-01-04
            相关资源
            最近更新 更多