2017-12-15 5 views
2

新しい質問ではないようです。しかし、私は本当のsolutioinを発見していない。ここ はそれがうまくいくと予想する私のコードです:PHP Laravel save()はレコードを更新しません

$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(); 
} 

私は$ペット[ 'pet_id']と$ pet_new [ 'pet_breed_id']は値を持っていることを確信しています。 そしてデータベースのテーブルpet_breedsがプライマリキーをpet_idとして持っていると確信しています。システムは私がpet_idと新しいpet_breed_idを得ることができるようにデータベースに接続することができます。 そして、私はモデルにtable_nameとprimaryKeyの値を上書きしていることを確信しています。

class pets extends Model 
{ 
    protected $table="pets"; 
    protected $primaryKey="pet_id"; 
} 

さらに更新されません。 今私はDB :: update()を直接使用して、問題を解決するために更新クエリを実行しています。 しかし、私はまだそれが起こっている理由を知りたいですか?それとも、コーディングに何か間違っていますか?または、現在の更新状況では保存機能を使用できません。

答えて

1

は、コレクションの代わりにオブジェクトを取得してください:

$pet = pets::find($pet['pet_id']); 

if (!is_null($pet)) { 
    $update_pet->pet_breed_id = $pet_new['pet_breed_id']; 
    $update_pet->save(); 
} 

はまた、あなたが右のコードの最初の行の後 dd($pet);を置くことによって、右のオブジェクトを取得していることを確認してください。

+1

と一致するすべてのレコードを更新する必要がある場合、私はそれをテストしているが、完全に働きました。どうもありがとう。^_ ^ –

0

結果を配列として返すgetメソッドを使用しているため、最初のメソッドを使用しないでください。 pet_idがプライマリキーの場合

$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(); 
} 

そして、あなたは$ update_pet-> first()の行番号3で何をしているのですか?

2

なぜ複雑になるのですか?また

pets::find($pet['pet_id'])->update(['pet_breed_id' => $pet_new['pet_breed_id']]); 

のいずれかの行が含ま:あなたのペットモデルクラスに

protected $fillable = ['pet_breed_id']; 

protected $guarded = []; 

またはこのいずれかを。

最後に、すべてのクラス名を資本で始める必要があります。モデル名は複数形であってはならない。したがって...

class Pet extends Model 
1

get()をfirst()に変更するだけで、1つのデータだけが返されます。

$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 

それとも、どこ条件、使用する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(); 
    } 
} 
関連する問題