일단 컬렉션을 조회한 후 반복문을 사용하면 되지 않을까요?
$collection = Model::where()->get(); foreach($collection as $item) { $item->field = 'new value'; $item->save(); }
모델이 다음과 같을 때...
<?php namespace App; use Illuminate\Database\Eloquent\Model; /** * @property int $id * @property string $title * @property string $content * @property int $user_id * @property User $user */ class Post extends Model { protected $fillable = [ 'title', 'content', ]; public function user() { return $this->belongsTo(User::class); } }
이걸 원하신 거 맞나요?
~/laravel-project $ php artisan tinker Psy Shell v0.8.1 (PHP 7.0.13 — cli) by Justin Hileman >>> use App\User; => null >>> use App\Post; => null >>> $user = User::first(); => App\User {#674 id: "1", name: "Brady Mante", email: "foo@bar.com", created_at: "2017-03-08 02:54:02", updated_at: "2017-03-08 02:54:02", } >>> $post = $user->posts()->create([...]); 'title' => 'Example title', 'content' => 'Hello Tinker', ]); => App\Post {#684 title: "Example title", content: "Hello Tinker", user_id: 1, updated_at: "2017-03-08 02:58:51", created_at: "2017-03-08 02:58:51", id: 2, } >>> $post->title = 'Modified title'; => "Modified title" >>> $post->content = 'Modified content'; => "Modified content" >>> $post->getOriginal(); => [ "title" => "Example title", "content" => "Hello Tinker", "user_id" => 1, "updated_at" => "2017-03-08 02:58:51", "created_at" => "2017-03-08 02:58:51", "id" => 2, ] >>> $post->getDirty(); => [ "title" => "Modified title", "content" => "Modified content", ] >>> $post->save(); => true >>> Post::find(2); => App\Post {#660 id: "2", title: "Modified title", content: "Modified content", user_id: "1", created_at: "2017-03-08 02:58:51", updated_at: "2017-03-08 02:59:44", }
save()를 사용해서 업데이트하고 싶습니다.
단, where조건이 여러개 일 때 사용하고 싶은데
찾아봤는데도 마땅한 정보를 찾지 못했습니다.
그래서 where함수로 찾은 후에 update([.....])를 사용했는데 save로는 어려울까요?
findOrFail이나 find나 firstOrFail같은 것들은 익명함수를 쓰지도 못하는 것 같고...
그냥 update()를 사용해야 하나요?