saveMany
機能を使用して現在のユーザーを保存することはできますか?現在のユーザーをComment
モデルに保存しようとしているためです。以下は私のコードです。私がボタンを提出しようとすると、それは言う。Insert Related Modelsを使用して現在のユーザーを保存できますか?
整合性制約違反:1452は、子行を追加または更新できません:外部キー制約が失敗する(
webdev
をcomments
、CONSTRAINTcomments_sender_id_foreign
FOREIGN KEY(sender_id
)DELETE CASCADE ONusers
(id
)を参照。)(SQL:挿入comments
(comment
、document_id
、updated_at
、created_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');
}
}
私はあなたのコードを試しましたが、それは言う。 'オーバーロードされたプロパティの間接的な変更App \ Models \ Comment :: $ commentは効果がありません ' – Francisunoxx
申し訳ありません私は私の答えを更新しました:) – Maraboc
ちょっとこれは動作します!この部分について何か教えてもらえますか? '$ commentObject-> sender_id = $ user-> id?' 'sender_id'は私のモデルの中のfillableですか? – Francisunoxx