我想更新数据库中的多行,并找到了一种方法。但这似乎不是最好的方法,因为目前它是在多个调用中进行的。
我现在想知道是否有更好的方法。
具有updatePersons
功能的homecontroller
:
<?php
class HomeController extends BaseController {
public function index()
{
$persons = Person::get();
return View::make('hello')
->with(compact('persons'));
}
public function updatePersons()
{
$persons = Person::get();
foreach ($persons as $person) {
$person->fname = Input::get('fname'.$person->id);
$person->lname = Input::get('lname'.$person->id);
$person->save();
}
return Redirect::route('home')->with('succes', 'Siden er opdateret');
}
}
具有形式的视图
@extends('layouts.master')
@section('content')
<div class="container">
<ul class="list-group">
{{ Form::open(array('route'=>'personUpdate', 'method' => 'post')) }}
@foreach ($persons as $person)
<li class="list-group-item">
{{ Form::text('fname'.$person->id,$person->fname,array('class'=>'form-control', 'placeholder'=>'fname')) }}
{{ Form::text('lname'.$person->id,$person->lname,array('class'=>'form-control', 'placeholder'=>'lname')) }}
</li>
@endforeach
<li class="list-group-item">
<div class="box-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</li>
{{ Form::close() }}
</ul>
</div>
</div>
@stop
路线:
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController@index'));
Route::post('/', array('as'=>'personUpdate', 'uses'=>'HomeController@updatePersons'));
在updatePersons()
中的foreach循环之后,我尝试在$persons
上使用savemany()
函数,但没有结果。
如果要更新多个行,每个行都有不同的值,那么没有更简单的方法了。
你能想到如何用SQL写这篇文章吗?