donglipi4495 2014-06-10 03:55
浏览 542

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

I'm trying to update existing entries in my MySQL database with eloquent's 'save()' method, but it keeps giving me the following error:

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

the save() method is supposed to detect the record via primary key and update the record instead of trying to insert it right? what am i missing here?

here is the beginning of my user model:

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;

this is how i created the users table: (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();
    });
}

And here is my controller method:

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();

    }
}

what is really throwing me off is if i use the User::find(objectguidofrecordhere) it works as expected and finds the record no problem.

  • 写回答

2条回答 默认 最新

  • douqiu1604 2014-06-10 05:04
    关注

    the save() method is supposed to detect the record via primary key and update the record instead of trying to insert it right?

    I do not believe that is how the save method works. You need to query for a model to determine its existence or not, then act accordingly:

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

    If the user is null, then it doesn't exist in the database and you have to create a new object. Then update whatever attributes you want. Then save it.

    As far as I know, save does not automatically determine if the objects exists already for you. I could be wrong if this is some hidden undocumented Eloquent feature though.

    评论

报告相同问题?