【发布时间】:2015-04-10 19:41:12
【问题描述】:
我有一个多对多关系,因此实现需要创建具有两个主键的新表 ,,
这是新表:
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']);
});
}
但是当尝试使用这个函数插入数据时: //将新的FriendShip插入数据库
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';
}
好的,它在数据库中创建新记录,但是虽然它返回了这个错误 PDO::lastInsertId() 期望参数 1 是字符串,给定数组
【问题讨论】:
-
您的意思是使用复合主键(由 2 个字段组成)创建一个新表
-
是的,我的意思是
-
首先,从您得到的错误来看,插入现有主键似乎不是问题,而是类型不兼容/不一致问题。您需要确保作为“User1Id”传递的内容是一个字符串(我不熟悉 PHP,不知道“给定数组”是什么意思)
-
"User1Id" 如你所见,是一个整数 >> $table->integer('user1_id')->index('fk_user_has_user_user1_idx');而且我确定我也以整数传递
-
我不知道 lastInsertId() 是哪个函数,但同样,它需要一个字符串参数,并得到其他东西。我只能从这里说这些了。