Column not found: 1054 Unknown column '0' in 'field list' - Laravel - I don't have a 0 column anywhere in my code

好久不见. 提交于 2020-12-29 05:38:24

问题


I'm getting this weird error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: update forum_threads set 0 = locked, 1 = 1, updated_at = 2016-03-17 16:01:59 where topic_id = 3 and forum_threads.deleted_at is null)

The thing is, I don't have a 0 column. I don't have a where clause with a 0 anywhere in my code. I am using a scope query.

My controller is:

    $action = $request->input('action');
    $topic = $request->input('topic');
    $thread = Thread::where('topic_id', $topic);

    switch ($action) {
        case ('locked'):
            $thread->lock();
            break;
    }

As you can see, I don't do much. I am just trying to lock a thread. I am calling the lock scope in my Thread model. I have a lot of switch cases, one of which is lock. I have run half of the query at the top so I don't have to repeat myself. I simply stored it in the $thread variable so that I can perform actions like $thread->delete() and $thread->restore().

My query scope in Thread model:

public function scopeLock($query)
{
    return $query->where('locked', 0)->update(['locked', 1]);
}

That's it. I think it may because I have a where clause passing from my controller (Thread::where('topic_id', $topic)) and I'm just continuing it onto my scope.

Any help is highly appreciated.


回答1:


The error is due to ->update(['locked', 1]); which should be ->update(['locked' => 1]);

the update function uses an array as "column" => "value", your syntax error causes Laravel to think [ 0 => 'locked', 1 => 1], so it translates to this SQL SET 0 = 'locked', 1 = 1...




回答2:


As I mentioned in the comment section, change your function to this:

public function scopeLock($query)
{
    return $query->where('locked', 0)->update(['locked' => 1]);
}

Note the changes in the update method.




回答3:


I had a double condition in WHERE

ContestPool::where(['contest_id', '=', $contest_id], ['user_id', '=', $user_id])->delete();

I fixed adding brackets for both conditions

ContestPool::where([['contest_id', '=', $contest_id], ['user_id', '=', $user_id]])->delete();



回答4:


in my case the problem was in the model attributes.I use protected $fillable, protect $foreignKey, protected $timestamp. to solve de problem, I put all the attributes in protect $fillable variable.



来源:https://stackoverflow.com/questions/36065951/column-not-found-1054-unknown-column-0-in-field-list-laravel-i-dont-ha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!