在 laravel 中更新 table 及其相关模型?
Update a table and its related model in laravel?
我有客户 table 和 client_address 信息 table。在更新下面给出的 client.my 模型 类 时,我需要更新两个 table,
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();
但是它不起作用,请您解释一下更新模型及其相关模型的最佳实践。
你可以做得更简单:
$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
我们也可以像下面@lukasgeiter 的回答那样使用批量赋值:
$client = Client::findOrFail($id);
$client->fill($request->all());
$client->addressInfo->fill($request->all());
$client->push();
我有客户 table 和 client_address 信息 table。在更新下面给出的 client.my 模型 类 时,我需要更新两个 table,
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();
但是它不起作用,请您解释一下更新模型及其相关模型的最佳实践。
你可以做得更简单:
$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
我们也可以像下面@lukasgeiter 的回答那样使用批量赋值:
$client = Client::findOrFail($id);
$client->fill($request->all());
$client->addressInfo->fill($request->all());
$client->push();