Mahmoud Nassar Mahmoud Nassar - 13 days ago 10
PHP Question

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

Answer

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