我想更新帖子的隐私
我的控制器
public function changePostsPrivacy(Request $request){
$userId = $request->user()->id;
$postid = $request->get('id');
//dd($postid);
$privacy = $request->get('privacy');//dd($privacy);
$user = User::where(['id' => $userId, 'hide' => 0])->first();
if($user && $postid && in_array($privacy, [1,0])){
DB::table('posts')->update(['creator_id' => $userId, 'id' => $postid],[
'privacy' => $privacy,
]);
}
}
路线:
Route::group(['middleware'=>['auth:api', \App\Http\Middleware\OnlyRegisteredUsers::class]], function(){
/**
* Group for registered users only APIs
*/
Route::post('changePostsPrivacy','UserController@changePostsPrivacy');
});
迁移
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->longText('content');
$table->string('short_description');
$table->unsignedInteger('media_id')->nullable();
$table->foreign('media_id')->references('id')->on('medias');
$table->unsignedInteger('creator_id');
$table->foreign('creator_id')->references('id')->on('users');
$table->boolean('hide')->default(0);
$table->timestamps();
});
}
此迁移中添加了新列
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->integer('privacy')->after('creator_id');
});
}
当我想在任何帖子中添加隐私时,都会给我一个错误
“消息”:“ SQLSTATE [23000]:违反完整性约束:1451 无法删除或更新父行:外键约束失败 ({
webdb
。comments
,约束comments_post_id_foreign
外键 (post_id
)参考posts
(id
))(SQL:更新posts
集creator_id
= 17,id
= 48)”,
答案 0 :(得分:5)
您也可以尝试这个。
$post = Post::where(['creator_id' => $userId, 'id' => $postid])->first();
$post->privacy = $privacy;
$post->save();
答案 1 :(得分:2)
您必须在更新隐私信息中使用where条件
DB::table('posts')->where(['creator_id' => $userId, 'id' => $postid])->update(['privacy' => $privacy])
答案 2 :(得分:2)
如果您有Post模型,则可以执行以下操作:
Post::where(['creator_id' => $userId, 'id' => $postid])->update(['privacy' => $privacy]);
为防止任何外键错误,应使用validation request检查提供的user_id
和post_id
exists。
答案 3 :(得分:0)
public function changePostsPrivacy(Request $request){
$userId = $request->user()->id;
$postid = $request->get('id');
$privacy = $request->get('privacy');
$user = User::where(['id' => $userId, 'hide' => 0])->first();
if($user && $postid && in_array($privacy, [1,0])){
DB::table('posts')->update([
'privacy' => $privacy,
]);
}
创建者ID和ID不需要更新。