【问题标题】:How to check for unique key when saving object to database in laravel?在laravel中将对象保存到数据库时如何检查唯一键?
【发布时间】:2013-08-12 14:09:28
【问题描述】:

我正在尝试保存到数据库,如果该帖子已经在数据库中,我希望忽略它。这就是我目前保存它的方式。 postid 必须是唯一的。

public function save($type, $postid, $url, $author, $content)
{
    $post = new Post;
    $post->type = $type;
    $post->postid = $postid;
    $post->url = $url;
    $post->author = $author;
    $post->content = $content;
    echo $post;

    $post->save();
}

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    在尝试保存之前,对您希望唯一的任何字段使用 Validator 类的 unique 验证规则。

    $input = array('postid' => $postid);
    $rules = array(
        'postid' => 'unique:posts,postid'
    );
    
    $validate = Validator::make($input,$rules);
    
    if($validator->passes())
    {
        $this->save($type, $postid, $url, $author, $content)
    } 
    else 
    {
        $messages = $validator->messages();
        echo $messages->first('postid');
    }
    

    【讨论】:

    • 注意$validate 应该是$validator。我试图编辑答案,但 SO 有一个荒谬的 6 个字符配额。
    【解决方案2】:

    如果帖子已经具有您要设置的唯一 ID,您可以使用 Post::findOrFail(UNIQUE_ID)try ... catch ... 结构中使用它来回退。

    【讨论】:

    • I do try{ Post::findOrFail($postid);}catch(... 似乎每次都会触发catch,即使$postid 是唯一的。
    【解决方案3】:

    您可以在验证中检查唯一性。我不确定您是否正在检查唯一的主要 postid。我建议您将 postid 保留为主键和自动增量。您可以匹配帖子标题以进行重复。

    $rules = array(
        'postid' => 'required|unique:posts'
    );
    
    $validator = Validator::make(Input::all(), $rules);
    
    if($validator->fails()){
        return Redirect::back()->withInput()->with('errors', $validator->messages());
    }else{
        $data = array(
            'type' => Input::get('type'),
            'postid' => Input::get('postid'),
            'url' => Input::get('url'),
            'author' => Input::get('author'),
            'content' => Input::get('content')
        );
    
        if(Post::create($data)){
            Session::flash('messages', 'Post created.');
            return Redirect::route('routename');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 2018-02-25
      • 2017-06-22
      • 2013-03-10
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 1970-01-01
      相关资源
      最近更新 更多