在laravel中更新一个表及其相关模型


Update a table and its related model in laravel?

我有客户端表和客户端地址信息表。当更新客户端时,我需要更新这两个表。我的模型类如下所示,

        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();