Mahmoud Nassar
Mahmoud Nassar

Reputation: 609

Getting error when trying to insert a record that has composite primary keys

I have a Many-to-Many relation, so the implementation require to create new table with two primary keys ,,

here's the new table :

public function up()
{

    Schema::create('friendship', function(Blueprint $table)
    {
        $table->integer('user1_id')->index('fk_user_has_user_user1_idx');
        $table->integer('user2_id')->index('fk_user_has_user_user2_idx');
        $table->boolean('state')->nullable();
        $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->primary(['user1_id','user2_id']);
    });
}

but when try to insert data using this function : //Insert new FriendShip into DataBase

public function InsertFriendShip($User1Id, $User2Id, $State)
{
    $friend = new FriendShip();

    $friend->User1_Id = $User1Id;
    $friend->User2_Id = $User2Id;
    $friend->State = $State;

    // save new FriendShip to the database
   if(!$friend->save())
       return 'created';
}

ok it create the new record in database but although it return this Error PDO::lastInsertId() expects parameter 1 to be string, array given

Upvotes: 0

Views: 868

Answers (2)

Didier
Didier

Reputation: 136

I encountered the same error. The lastInsertId call is done for autoincrementing tables. They by definition have only simple primary_keys.

If you add in your model

protected $primaryKey = ['FIELD1', 'FIELD2'];
public $incrementing = false;

Then it should work, it did for me. Now it won't call lastInsertId

Upvotes: 1

Bogdan
Bogdan

Reputation: 44546

From what I can deduce, you have a Friendship Eloquent Model attached to the friendship pivot table. The problem with that is that Eloquent doesn't work with composite primary keys, so there's no real way of doing that.

You should have a look at the Laravel Eloquent Docs to see how to implement many-to-many relationships. In you case you could have a User model that looks something like this:

class User extends Eloquent {

    public function friends()
    {
        return $this->belongsToMany('User', 'friendship', 'user1_id', 'user2_id');
    }

    public function addFriend(User $user)
    {
        $this->friends()->attach($user->id);
    }

    public function removeFriend(User $user)
    {
        $this->friends()->detach($user->id);
    }

}

You can then add or remove a friend for any user very easily:

$user1 = User::find($id1);
$user2 = User::find($id2);

$user1->addFriend($user2);
//or
$user1->removeFriend($user2);

Upvotes: 2

Related Questions