我想我可以使用saveMany
功能保存当前用户吗?因为我试图将当前用户保存在我的Comment
模型中。这是我的代码,如下所示。当我试图提交按钮时,它说。
完整性约束违规:1452无法添加或更新子行:外键约束失败(
webdev
。comments
,CONSTRAINTcomments_sender_id_foreign
FOREIGN KEY(sender_id
)参考users
(id
)ON DELETE CASCADE)(SQL:插入comments
comment
,document_id
,updated_at
,created_at
)值(dasdsa,161,2016-07-29 17:11:05,2016-07-29 17:11:05))
控制器:
class CommentController extends Controller
{
public function postComments(Request $request, Document $id)
{
$this->validate($request,
[
'comment' => 'required',
]);
$commentObject = new Comment();
$user = Auth::user();
$commentObject->comment = $request->comment;
$id->comments()->saveMany([$commentObject, $user->id]);
return redirect()->back();
}
}
型号:
注释
class Comment extends Model
{
protected $tables = 'comments';
protected $fillable =
[
'comment',
'document_id',
'sender_id',
];
public function documents()
{
return $this->belongsTo('App\Models\Document');
}
public function users()
{
return $this->belongsTo('App\Models\Comment');
}
}
用户
class User extends Model implements AuthenticatableContract
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}
答案 0 :(得分:0)
你应该这样做:
$id->comments()->saveMany([$comment1, $comment2]);
在调用saveMany
方法之前,您还应该将user_id
添加到评论对象中:
$commentObject->sender_id = $user->id
我认为在您的情况下,您不需要saveMany
只能使用save
:)
$id->comments()->save($commentObject);