我想更新我的记录,如果它存在,但创建一个新的,如果不存在。这是我到目前为止的进展:
MerchantBranch.php
public function token()
{
return $this->hasOne('App'MerchantBranchToken');
}
MerchantBranchToken.php
public function merchant_branch()
{
return $this->belongsTo('App'MerchantBranch');
}
$find = MerchantBranchToken::find($id);
if (!$find) {
$branch = new MerchantBranchToken(['token' => $token]);
MerchantBranch::find($id)->token()->save($branch);
} else {
$find->token = $token;
$find->save();
}
它工作得很好。
但据我所知,Laravel非常强大,因为它有雄辩的模型。我能剪短一点吗?还是我已经做对了?
我已经尝试使用"updateOrCreate"方法,但我的外键"merchant_branch_id"需要是可填写的。
Laravel提供方法updateOrCreate用于此目的
-
如果有从奥克兰到圣地亚哥的航班,设置价格为99美元。
-
如果没有匹配的模型,创建一个
$flight = App'Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
Laravel已经通过save
函数使用了这种方法
$user->save()
Laravel代码// If the model already exists in the database we can just update our record
// that is already in this database using the current IDs in this "where"
// clause to only update this model. Otherwise, we'll just insert them.
if ($this->exists)
{
$saved = $this->performUpdate($query);
}
// If the model is brand new, we'll insert it into our database and set the
// ID attribute on the model to the value of the newly inserted row's ID
// which is typically an auto-increment value managed by the database.
else
{
$saved = $this->performInsert($query);
}
https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Eloquent/Model.php L1491
->exists
所有laravel模型都有一个->exists
属性。
更具体地说,如果模型是从数据库中加载的,或者自从创建以来已经保存到数据库中,那么exists
属性将为真;否则为false。
如果你理解->exists
,你可以使用它,但这里有另一种方法来处理这样的要求。
另一种方式。
/**
* Create or update a record matching the attributes, and fill it with values.
*
* @param array $attributes
* @param array $values
* @return static
*/
public static function updateOrCreate(array $attributes, array $values = array())
{
$instance = static::firstOrNew($attributes);
$instance->fill($values)->save();
return $instance;
}
非常简单。
第一个查找记录然后删除它再次插入
$record = Model::where(['id'=>1]);
if ($record->exists()) {
$record->delete();
}
Model::create($request->all());
添加新的函数代码:
供应商/laravel/框架/src/照明/数据库/的/Builder.php:
public function updateOrInsert(array $attributes, array $values = [])
{
$instance = $this->where($attributes);
if ($instance->count() != 0) {
$instance->update($values);
} else {
$instance = $this->updateOrCreate($attributes, $values);
}
return $instance;
}