Laravel save()方法无法正确检测自定义主键

时间:2014-06-10 03:55:04

标签: php mysql laravel eloquent

我试图用滔滔不绝的' save()'来更新MySQL数据库中的现有条目。方法,但它一直给我以下错误:

Illuminate \ Database \ QueryException
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

save()方法应该通过主键检测记录并更新记录而不是试图插入它吗?我在这里失踪了什么?

这是我的用户模型的开头:

class User extends Eloquent implements UserInterface, RemindableInterface {

use UserTrait, RemindableTrait;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

protected $primaryKey = 'objectguid';

public $incrementing = false;

这就是我创建用户表的方式:( laravel migration)

    public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        $table->string('objectguid')->primary();
        $table->string('username');
        $table->string('email');
        $table->string('firstname');
        $table->string('lastname');
        $table->string('displayname');
        $table->string('company');
        $table->string('department');
        $table->string('title');
        $table->integer('phone');
        $table->date('start_date');
        $table->timestamps();
    });
}

这是我的控制器方法:

public function pull()
{

    $users = $this->ldap->search([
        'objectguid', 'samaccountname', 'mail', 'title',
        'sn', 'givenname', 'displayname', 'department',
        'company', 'telephonenumber', 'whencreated'
    ])->get();

    foreach($users as $user)
    {

        $user->save();

    }
}

真正让我失望的是,如果我使用User::find(objectguidofrecordhere)它按预期工作并且发现记录没有问题。

2 个答案:

答案 0 :(得分:1)

  

save()方法应该通过主键检测记录   更新记录而不是试图插入它?

我不相信保存方法的工作原理。您需要查询模型以确定其存在与否,然后采取相应措施:

$user = User::find(1234);

if ( is_null($user) ) {
  // User doesn't exist
  $user = new User();
}
$user->someAttribute = 'taco';
$user->save();

如果用户是null,那么它在数据库中不存在,您必须创建一个新对象。然后更新所需的任何属性。然后保存。

据我所知,save不会自动确定对象是否已经存在。如果这是一些隐藏的无证件Eloquent功能,我可能会错。

答案 1 :(得分:1)

以下是我为解决这个问题所做的工作。由于我最初没有使用Eloquent从MySQL数据库中检索模型,因此它不会更改exists模型实例中的User标记,因此save()方法仍然认为数据库中不存在该模型。

我在我的User模型中添加了以下方法来解决此问题。

public function checkExistence()
{
    if( ! is_null(User::find($this->objectguid)))
    {
        $this->exists = true;
        return true;
    }

    return false;
}

并将我的控制器方法改为:

public function pull()
{

    $users = $this->ldap->search([
        'objectguid', 'samaccountname', 'mail', 'title',
        'sn', 'givenname', 'displayname', 'department',
        'company', 'telephonenumber', 'whencreated'
    ])->get();

    foreach($users as $user)
    {

        $user->checkExistence();
        $user->save();

    }

    return View::make('ldap.display', ['users' => $users]);

}

再次感谢大家的意见,并帮助我找到解决方案。

相关问题