laravel 在laravel中更新表格及其相关模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28783499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update a table and its related model in laravel?
提问by gsk
I have client table and client_address info table. I need to update both table when updating client.my model classes given below,
我有客户端表和 client_address 信息表。更新下面给出的 client.my 模型类时,我需要更新两个表,
class Client extends Model {
public function addressInfo() {
return $this->hasOne('App\Model\ClientAddressInfo');
}
}
class ClientAddressInfo extends Model {
protected $table = 'client_address_info';
public function client() {
return $this->belongsTo('App\Model\Client');
}
}
My controller for updating is given below.
我的更新控制器如下。
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$address = ClientAddressInfo::where('client_id', '=', $id)->get();
$address->street = "new street";
$address->save();
But it is not working,Could you please explain the best practice for updating model and its related models.
但它不起作用,请您解释更新模型及其相关模型的最佳实践。
回答by lukasgeiter
You can do this much simpler:
你可以更简单地做到这一点:
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$client->addressInfo->street = 'new street';
$client->addressInfo->save();
$client->save();
Instead of calling save()
on both models you can also use push()
which will save the model and all it's related models:
save()
您还可以使用push()
which 来保存模型及其所有相关模型,而不是同时调用这两个模型:
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$client->addressInfo->street = 'new street';
$client->push(); // save client and addressInfo
回答by im_tsm
Also we can use mass assignment like following in the answer by @lukasgeiter:
我们也可以在@lukasgeiter 的回答中使用如下的批量赋值:
$client = Client::findOrFail($id);
$client->fill($request->all());
$client->addressInfo->fill($request->all());
$client->push();