我可以使用插入相关模型保存当前用户吗?

时间:2016-07-29 17:17:01

标签: php laravel laravel-5.2

我想我可以使用saveMany功能保存当前用户吗?因为我试图将当前用户保存在我的Comment模型中。这是我的代码,如下所示。当我试图提交按钮时,它说。

  

完整性约束违规:1452无法添加或更新子行:外键约束失败(webdevcomments,CONSTRAINT comments_sender_id_foreign FOREIGN KEY(sender_id)参考usersid)ON DELETE CASCADE)(SQL:插入comments commentdocument_idupdated_atcreated_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');
  }
}

1 个答案:

答案 0 :(得分:0)

documentation

相关

你应该这样做:

$id->comments()->saveMany([$comment1, $comment2]);

在调用saveMany方法之前,您还应该将user_id添加到评论对象中:

$commentObject->sender_id = $user->id

我认为在您的情况下,您不需要saveMany只能使用save:)

$id->comments()->save($commentObject);