简体   繁体   English

在Laravel 5.3中更新属于关系

[英]Updating BelongsTo Relationships in Laravel 5.3

everyone, i have table statuses with fields id , user_id , parent_id , body . 大家好,我的表格状态iduser_idparent_idbody
now the status table has relations with user like this : 现在状态表与用户的关系如下:

Status Model 状态模型

    public function user() {
        return $this->belongsTo('App\User', 'user_id');
    }

    public function scopeNotReply($query) {
        return $query->whereNull('parent_id');
    }

    public function replies() {
        return $this->hasMany('App\Status', 'parent_id');
    }

User Model 用户模型

public function statuses() {
    return $this->hasMany('App\Status', 'user_id');
}

but, unfortunately i can't access the user_id when i want to reply the status and save into database with same table statuses . 但是,不幸的是,当我想回复状态并将其保存到具有相同表statuses数据库中时,我无法访问user_id I use the associate method and the StatusController is like this : 我使用associate方法,并且StatusController是这样的:

public function postReply(Request $request, $statusId){
    $this->validate($request, [
        "reply-{$statusId}" => 'required|max:1000',
    ]);

    $status = Status::notReply()->find($statusId)->first();

    $reply = Status::create([
        'body'  => $request->input("reply-{$statusId}"),
    ])->user()->associate(Auth::user());

    $status->replies()->save($reply);

    return redirect()->back();
}

everytime i try to reply the status, i got this error message SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value . 每次我尝试回复状态时,都会收到此错误消息SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value

Could anybody to help me to solve this problem ?? 有人可以帮助我解决这个问题吗?

Thank You 谢谢

The reason you're getting this error is because you're creating the Status before the user_id has been associated with it. 出现此错误的原因是因为您是在与user_id关联之前创建Status的。

One way to get around this would be to move the user_id logic inside the create array ie: 解决此问题的一种方法是将user_id逻辑移至create数组内,即:

Status::create([
    'body'    => $request->input("reply-{$statusId}"),
    'user_id' => Auth:user()->id
]);

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM