2016-07-29 5 views
0

saveMany機能を使用して現在のユーザーを保存することはできますか?現在のユーザーをCommentモデルに保存しようとしているためです。以下は私のコードです。私がボタンを提出しようとすると、それは言う。Insert Related Modelsを使用して現在のユーザーを保存できますか?

整合性制約違反:1452は、子行を追加または更新できません:外部キー制約が失敗する(webdevcomments、CONSTRAINT comments_sender_id_foreign FOREIGN KEY(sender_id)DELETE CASCADE ON usersid)を参照。)(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'); 
} 
} 

ユーザーdocumentationに関連

class User extends Model implements AuthenticatableContract 
{ 
    public function comments() 
    { 
    return $this->hasMany('App\Models\Comment'); 
    } 
} 

答えて

0

:あなたはこのようにそれを行う必要があります

あなたは saveManyだけ saveを使用することができます:)

を必要としない、あなたのケースで

$commentObject->sender_id = $user->id 

と私は思う:

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

そして、あなたはまた、コメントオブジェクトにuser_idを追加する必要がありsaveManyメソッドを呼び出す前に

+0

私はあなたのコードを試しましたが、それは言う。 'オーバーロードされたプロパティの間接的な変更App \ Models \ Comment :: $ commentは効果がありません ' – Francisunoxx

+0

申し訳ありません私は私の答えを更新しました:) – Maraboc

+0

ちょっとこれは動作します!この部分について何か教えてもらえますか? '$ commentObject-> sender_id = $ user-> id?' 'sender_id'は私のモデルの中のfillableですか? – Francisunoxx

関連する問題