2014-02-19 77 views
0

我对Laravel有这个问题:Laravel更新或创建项目

我有我的模型和我的RestfulAPI控制器。

进入store()方法我会检查是否有一个已经有'myField'字段(myField id不同于'id')的元素等于我必须创建的元素。如果它已经存在,那么我想更新,否则我会简单地创建(save())。

我有使用find()方法吗?

回答

0

根据我的经验,你必须遍历表并检查唯一性。 你可以创建你的帮助函数,并使用类似array_unique函数。也许值得检查Validator类是如何检查用户输入是唯一的。

0

目前我们有firstOrCreatefirstOrNew,但我不认为他们真的适合您的需求。例如,firstOrCreate将尝试通过所有属性找到一行,而不仅仅是一些,所以在这种情况下的更新是没有意义的。所以我觉得你真的不得不寻找它,但你可以创建一个BaseModel并创建一个createOrUpdate方法可能看起来像这样的:

这是未经测试的代码

class BaseModel extends Eloquent { 

    public function createOrUpdate($attributes, $keysToCheck = null) 
    { 
     // If no attributes are passed, find using all 
     $keysToCheck = $keysToCheck ?: $attributes; 

     if ($model = static::firstByAttributes(array_only($keysToCheck, $attributes)) 
     { 
      $model->attributes = $attributes; 
      $model->save(); 
     } 
     else 
     { 
      $model = static::create($attributes); 
     } 

     return $model; 
    } 

} 

这是一个实现它:

class Post extends BaseModel { 

    public function store() 
    { 
     $model = $this->createOrUpdate(Input::all(), ['full_name']); 

     return View::make('post.created', ['model' => $model]); 
    } 

}