我正在尝试保存或更新,在检索多个记录时,但无法使其正常工作..
执行此操作时,首先看起来有效:
$c = Customer::select('Name', 'City');
$c[0]->update(array('Name' => 'new Name'));
var_dump($c[0]['Name']);
但经过刷新和测试之后,我仍然会看到旧名称:
$c = Customer::select('Name', 'City');
var_dump($c[0]['Name']);
有人知道我在做什么wrog?
我找回了json的东西:
data[0][Name]:Afrifield Corporation
data[0][City]:Maidstone
data[1][Name]:Amann Informatik AG
data[1][City]:Reinach BL
data[2][Name]:Antarcticopy
data[2][City]:Antwerpen
如果还有要使用此检索到的数组更新的列名称和城市..
所以最后一个问题没有比:
更快的解决方案 $custNo = Customer::select('Name', 'No_')->get();
for ($i = 0; $i < count($custNo); $i++) {
$c = Customer::select('Name', 'City')->where('No_','=',$custNo[$i]->No_);
$c->update(array('Name' => $input['data'][$i]['Name']));
}
No_是我的PrimaryKey我也在模型类中设置了它..
答案 0 :(得分:0)
而不是get()
和$c[0]
,请尝试使用first()
。您还需要在更新后重新获取。它是对象,而不是数组。因此,除非您将其更改为数组,否则$c['Name']
将无效。
$customers = Customer::select('Name', 'City')->where('No_','=','DKT000142')->get();
foreach ($customers as $customer) {
$customer->update(array('Name' => 'new Name'));
//you need to re-fetch for the updated data, assuming you have an id field
$currentCustomer = Customer::find($customer->id);
echo var_dump($currentCustomer->Name);
}
编辑:同样对于批量更新,您可以尝试类似:
$update = Customer::where('No_','=','DKT000142')->update(array('Name' => 'new Name'));
Edit2:要获得批量更新并获得更新记录,这是我能想到的最佳方法:
//First, we mass-update
$update = Customer::where('No_','=','DKT000142')->update(array('Name' => 'new Name'));
//Then we get the updated data and loop:
$customers = Customer::select('Name', 'City')->where('No_','=','DKT000142')->get();
foreach ($customers as $customer) {
echo var_dump($currentCustomer->Name);
}
答案 1 :(得分:0)
$c[0]->name = "New name";
$c[0]->save();