我有客户端表和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');
}
}
我的控制器更新如下。
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$address = ClientAddressInfo::where('client_id', '=', $id)->get();
$address->street = "new street";
$address->save();
但它不起作用,请你解释一下更新模型及其相关模型的最佳实践。
答案 0 :(得分:9)
你可以做得更简单:
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$client->addressInfo->street = 'new street';
$client->addressInfo->save();
$client->save();
您可以使用save()
来保存模型及其相关模型,而不是在两个模型上调用push()
:
$client = Client::findOrFail($id);
$client->name = rand(0, 1222222);
$client->addressInfo->street = 'new street';
$client->push(); // save client and addressInfo
答案 1 :(得分:0)
我们也可以在@lukasgeiter的答案中使用如下所示的质量分配:
$client = Client::findOrFail($id);
$client->fill($request->all());
$client->addressInfo->fill($request->all());
$client->push();