【问题标题】:“Call to undefined method stdClass::delete()” error while trying delete a row in Laravel尝试在 Laravel 中删除一行时出现“调用未定义的方法 stdClass::delete()”错误
【发布时间】:2015-06-24 06:55:25
【问题描述】:

从表中删除行时遇到问题。

问题似乎与this question 非常相似,但并没有解决问题。

我的控制器功能如下:

public function favourites() {

        //get relevant data for DB insert
        $spot_id = Input::get('spot_id');
        $user_id = Auth::user()->id;

        //query DB if favourite exists
        $query = DB::table('favourites')
            ->where('spot_id', '=', $spot_id)
            ->where('user_id', '=', $user_id);

        $check_favourites = $query->first();

        if (is_null($check_favourites)) {
            //doesnt exist - create record
            $favourite              = new Favourite;
            $favourite->spot_id     = $spot_id;
            $favourite->user_id     = $user_id;
            $favourite->save();

            //return ajax true
            return json_encode(true);               

        } else {
            // exists - delete record
            $check_favourites->delete();
            //return ajax false
            return json_encode(false);      
        }

}

我正在使用 Laravel 4.2

提前致谢

【问题讨论】:

    标签: php mysql database laravel laravel-4


    【解决方案1】:

    要使用 Eloquent delete() 方法,您需要使用 Eloquent,而不是 Query Builder

    代替:

    //query DB if favourite exists
    $query = DB::table('favourites')
        ->where('spot_id', '=', $spot_id)
        ->where('user_id', '=', $user_id);
    
    $check_favourites = $query->first();
    

    应该是:

    $check_favourites = Favourite::where('spot_id', '=', $spot_id)
        ->where('user_id', '=', $user_id)
        ->first();
    

    注意:查询生成器上可用的所有方法也都可用 查询 Eloquent 模型时。

    【讨论】:

    • 我认为这可能很愚蠢。完美运行,谢谢
    【解决方案2】:

    您有两个选择,@limonte 的答案(我更喜欢)或使用 id 运行删除查询:

    DB::table('favourites')->delete($check_favourites->id);
    

    【讨论】:

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