在laravel中将对象保存到数据库时如何检查唯一键?

Him*_*ors 1 laravel eloquent laravel-4

我正在尝试保存到数据库,如果它已经在数据库中,我希望忽略该帖子。这就是我目前保存它的方式。的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();
}
Run Code Online (Sandbox Code Playgroud)

use*_*496 5

在尝试保存之前,对您希望唯一的任何字段使用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');
}
Run Code Online (Sandbox Code Playgroud)