Laravel Eloquent 不只更新插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17154210/
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-14 07:59:02  来源:igfitidea点击:

Laravel Eloquent doesn't update only inserting

phplaravellaravel-4

提问by kim larsen

I am facing some problems with PHP Laravel update function. It doesn't update, only insert.

我在 PHP Laravel 更新功能方面遇到了一些问题。它不更新,只插入。

 public function post_rate(){
    $o = Input::all();

    //has user already rated?!
    $query = DB::table("ratings")->select("id")->where("user", "=", Auth::user()->id)->where("story_id", "=", $o['story_id'])->get();
    foreach ( $query as $d):
        $theID = $d->id;
    endforeach;
    if ( empty($query)):  //User hasn't rated!
           $z = new Rating(); 
    else: 
          $z = new Rating($theID);  //user has rated, tell which to update  
-----------------------------^ that cause the problem!
     endif;

        $z->story_id = $o['story_id'];
        $z->user = Auth::user()->id;
        $z->rating = $o['rating'];
        $z->save();

         echo "OK";

}

It works when no rows founded, but when i will use new Rating(@something) it fails.

它在没有建立行时工作,但是当我使用 new Rating(@something) 时它会失败。

the column id in "ratings" table is primary and auto_increment.

“ratings”表中的列id是primary和auto_increment。

In my model i have also set up

在我的模型中,我还设置了

 public static $key = 'id';

The output "$theID" also contains the correctly ID for the mysql row.

输出“$theID”还包含 mysql 行的正确 ID。

回答by Half Crazed

Try: $z = Rating::find($theID)with ->first()or ->get()instead

尝试:$z = Rating::find($theID)->first()->get()代替

回答by coffe4u

$z = Rating::find($theID);

or

或者

$z = Rating::where('id', '=', $theID)->first();

Both are equivalent.

两者是等价的。

回答by saran banerjee

In order to update in laravel simply use the command

为了在 Laravel 中更新,只需使用命令

Rating::where('id','=',$theID)->update(array('name'=> $name));

I hope this can be of some help.

我希望这能有所帮助。

回答by Luiz Alb Silva

The dude !

伙计!

I was taking the same problem. Checking out the source code, I found that the correct field to set the primary key name is 'primarykey'.

我遇到了同样的问题。查看源代码,我发现设置主键名称的正确字段是“primarykey”。

For example:

例如:

class User extends Eloquent {
    protected $table = 'users';
    protected $primaryKey = 'ID';
    public $timestamps = false;
}

回答by Mehdi Maghrooni

Take it easy!
take a look at this , when user hasn't rated you just save it as you did before !

把它容易
看看这个,当用户没有评分时,您只需像以前一样保存它!

if ( empty($query)){  //User hasn't rated!
        $z = new Rating();    
        $z->story_id = $o['story_id'];
        $z->user = Auth::user()->id;
        $z->rating = $o['rating'];
        $z->save();
}

and in the updatepart ! do as follows :

并在更新部分!做如下:

 else{
    $rates = array(
                'story_id' => $o['story_id'],
                'user' => Auth::user()->id,
                'rating' => $o['rating'],
            );
$old = Rating::find($theID);
$old->fill($rates);
$old->save();
}

回答by Gilberto Alexandre

For registration, Eloquent was not running the update because the method I used (see below) did not set the exists attribute to true. This is because I was getting all the fields returned ($ request-> all) from the request and creating a model, but that does not enable the object to update.

对于注册,Eloquent 没有运行更新,因为我使用的方法(见下文)没有将 exists 属性设置为 true。这是因为我从请求中获取了返回的所有字段($ request-> all)并创建了一个模型,但这并不能使对象更新。

This did not work

这没有用

$produto = new Produto($request->all());
$produto->update();

This also did not work

这也不起作用

$produto = new Produto($request->all());

$produtoToUpdate = Produto::find($this->id);
$produtoToUpdate->update(get_object_vars($produto));

Never use get_object_var, Eloquent Model has virtual attribute (you get with getAttributes), so get_object_vardid not return your fields.

永远不要使用get_object_varEloquent模型有虚拟属性(你用 getAttributes 得到),所以get_object_var没有返回你的字段。

This work!!

这个作品!!

$produto = new Produto($request->all());

if ($this->id <= 0 )
{
    $produto->save();
} else
{
    $produto->exists = true;
    $produto->id = $this->id;
    $produto->update();
}

回答by Ravi Ranjan

I also faced same problem, so it turns out to be eloquent model issue.

我也遇到了同样的问题,所以结果证明是雄辩的模型问题。

First of all add a protected array name fillable in your model and define the attributes.Like

首先在模型中添加一个可填充的受保护数组名称并定义属性。比如

protected $fillable = array('story_id', 'rating');

There are many way to update table in Laravel in your case.

在您的情况下,有很多方法可以在 Laravel 中更新表。

1. $requestedRating = Rating::findOrFail($id)->first()->update($request->all()); // No need for first if the id is unique.

2.  $requestedRating = Rating::findOrFail($id)->get()->update($request->all()); // fetch records from that model and update.

3. $requestedRating = Rating::whereIn('id', $id)->update($request->all()); 

In place of update you can also use fill like.

您还可以使用填充来代替更新。

1. $requestedRating = Rating::findOrFail($id)->first()->fill($request->all())->save();

There is always DB::table method but use this only when no option is available.

总是有 DB::table 方法,但只有在没有选项可用时才使用它。