2016-07-29 72 views
0

我在想我可以使用saveMany函數保存當前用戶嗎?因爲我試圖將我當前的用戶保存在我的Comment模型中。下面是我的代碼。當我試圖提交按鈕時說。我可以使用「插入相關模型」保存當前用戶嗎?

完整性約束違規:1452不能添加或更新子行,外鍵約束失敗(webdevcomments,約束comments_sender_id_foreign外鍵(sender_id)參考文獻usersid)ON DELETE CASCADE)(SQL:插入commentscommentdocument_idupdated_atcreated_at)值(dasdsa,161,2016年7月29日17時11分05秒,2016年7月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

相關的documentation

你應該做的是這樣的:

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

而之前調用saveMany方法,你也應該添加user_id到註釋對象:

$commentObject->sender_id = $user->id 

,我認爲你的情況,你不需要saveMany只有save可以用:)

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

我試過你的代碼,但它說的。 '間接修改重載屬性應用程序\模型\評論:: $評論沒有影響' – Francisunoxx

+0

對不起,我更新了我的答案:) – Maraboc

+0

嘿這個作品!你能告訴這件事嗎? '$ commentObject-> sender_id = $ user-> id?'sender_id'是否可以在我的模型中填充? – Francisunoxx

相關問題