简体   繁体   中英

Laravel Eloquent doesn't update only inserting

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

 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.

the column id in "ratings" table is primary and 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.

尝试: $z = Rating::find($theID) ,而不是->first()->get()

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

or

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

Both are equivalent.

In order to update in laravel simply use the command

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

I hope this can be of some help.

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'.

For example:

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

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 update part ! 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();
}

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.

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_var did not return your fields.

This work!!

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM