laravel 如何更新laravel中的列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24109535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:50:17  来源:igfitidea点击:

How to update column value in laravel

laravellaravel-4eloquent

提问by Alexander Kim

I have a page model. It has following columns in database table:

我有一个页面模型。它在数据库表中有以下列:

  • id
  • title
  • image
  • body
  • ID
  • 标题
  • 图片
  • 身体

I want to update only "image" column value.

我只想更新“图像”列值。

Here's my code:

这是我的代码:

public function delImage($path, $id) {
    $page = Page::find($id);
    $page->where('image', $path)->update(array('image' => 'asdasd'));
    \File::delete($path);
}

it throws me an error, that i am trying to use where() on a non-object. How can i correctly update my "image" column value?

它给我一个错误,我试图在非对象上使用 where()。如何正确更新我的“图像”列值?

回答by The Alpha

You may try this:

你可以试试这个:

Page::where('id', $id)->update(array('image' => 'asdasd'));

There are other ways too but no need to use Page::find($id);in this case. But if you use find()then you may try it like this:

还有其他方法,但Page::find($id);在这种情况下不需要使用。但是如果你使用find()那么你可以这样尝试:

$page = Page::find($id);

// Make sure you've got the Page model
if($page) {
    $page->image = 'imagepath';
    $page->save();
}

Also you may use:

你也可以使用:

$page = Page::findOrFail($id);

So, it'll throw an exception if the model with that id was not found.

因此,如果未找到具有该 id 的模型,它将引发异常。

回答by S. Guy

I tried to update a field with

我试图用

$table->update(['field' => 'val']);

But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"

但它不起作用,我不得不修改我的表模型以授权编辑此字段:在数组“protected $fillable”中添加“field”

Hope it will help someone :)

希望它会帮助某人:)

回答by Cubiczx

Version 1:

版本 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:

版本 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:

在回答问题的情况下,您可以使用它们:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();