Reputation: 386
Looks like that is not the new question. But I have not found out any real solutioin. Here is my code to expected it will work:
$update_pet=pets::where("pet_id",$pet['pet_id'])->get();
if($update_pet->count()>0){
$update_pet=$update_pet->first();
$update_pet->pet_breed_id=$pet_new['pet_breed_id'];
$update_pet->save();
}
I am sure that $pet['pet_id'] and $pet_new['pet_breed_id'] has value. And I am sure table pet_breeds in database has primary key as pet_id. The system can connect the database as I can get the pet_id and new pet_breed_id. And I am sure I have overwrite table name and primaryKey value in model.
class pets extends Model
{
protected $table="pets";
protected $primaryKey="pet_id";
}
And it does not updated even. Per now I am just directly using DB::update() to run the update query to solve the problem. But I still want to know why it is happening? Or is it something wrong in the coding? Or the save function cannot used in update situation now?
Upvotes: 3
Views: 3389
Reputation: 453
You only need to change get() to first() so it will only return one data.
$update_pet=pets::where("pet_id",$pet['pet_id'])->first();
if($update_pet->count()>0){
$update_pet=$update_pet->first();
$update_pet->pet_breed_id=$pet_new['pet_breed_id'];
$update_pet->save();
}e
Or if you need to update all the record that match with where condition, use foreach
$update_pet=pets::where("pet_id",$pet['pet_id'])->get();
foreach ($update_pet as $pet) {
if($pet->count()>0){
$pet=$update_pet->first();
$pet->pet_breed_id=$pet_new['pet_breed_id'];
$pet->save();
}
}
Upvotes: 1
Reputation: 15579
Why make things complicated?
pets::find($pet['pet_id'])->update(['pet_breed_id' => $pet_new['pet_breed_id']]);
Also either include this line:
protected $guarded = [];
or this one:
protected $fillable = ['pet_breed_id'];
in your pets model class.
One last thing, you should start all your classes name with capital. And model names should not be a plural. So...
class Pet extends Model
Upvotes: 2
Reputation: 752
You using get method which gives you result as an array so don't do that using first method. If pet_id is your primary key.
$update_pet=pets::where("pet_id",$pet['pet_id'])->first();
if($update_pet->count()>0){
$update_pet=$update_pet->first();
$update_pet->pet_breed_id=$pet_new['pet_breed_id'];
$update_pet->save();
}
and what is kind of stuff you are doing $update_pet->first() in line no 3 .
Upvotes: 0
Reputation: 163978
Try to get an object instead of collection:
$pet = pets::find($pet['pet_id']);
if (!is_null($pet)) {
$update_pet->pet_breed_id = $pet_new['pet_breed_id'];
$update_pet->save();
}
Also, make sure you're getting the right object by putting dd($pet);
right after the first line of the code.
Upvotes: 1