我想投票或其他人张贴的帖子。用户将 上传帖子,i
迁移到投票表
public function up()
{
Schema::create('votes', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts');
$table->integer('vote');
$table->boolean('hide')->default(0);
$table->timestamps();
});
}
路由文件
api.php
Route::group(['middleware'=>[
'auth:api', \App\Http\Middleware\OnlyRegisteredUsers::class]
], function(){
/**
* Group for registered users only APIs
*/
Route::post('saveMedia','UserController@saveMedia');
Route::post('voteToPost','UserController@voteToPost');
});
控制器
public function voteToPost(Request $request)
{
$userid = $request->user()->id;
$postid = $request->get('post_id');
$vote = $request->get('vote');
$votecount = DB::table('votes')->where('user_id', $userid)->where('post_id', $postid)->wherea('hide', 0)->count();
if($votecount == 0){
DB::table('votes')
->leftJoin('users', 'users.id', '=', 'votes.user_id')
->leftJoin('posts', 'posts.id', '=', 'votes.post_id')
->where(['votes.hide' => 0, 'votes.user_id' =>$userid, 'votes.post_id' =>$postid])
->updateOrInsert([
'user_id' => $userid,
'post_id' => $postid,
'vote' => $vote,
'hide' => 0,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
}
}
我遇到以下错误 “ message”:“ SQLSTATE [23000]:违反完整性约束:1052 where子句中的列'hide'不明确(SQL:select exist(select * from
votes
在{{1}上左联接users
}。users
=id
。votes
在user_id
上左加入posts
。posts
=id
。votes
其中(post_id
。votes
= 0和hide
。votes
= 3和user_id
。votes
= 6)和({{1} } = 3且post_id
= 6且user_id
= 1且post_id
= 0且vote
= 2018-10-05 11:44:38和hide
= 2018-10-05 11:44:38))为created_at
)“,
答案 0 :(得分:0)
public function voteToPost(Request $request){
$userid = $request->user()->id;
$postid = $request->get('post_id');
$vote = $request->get('vote');
$user = User::where(['id'=>$userid, 'hide'=>0])->first();
$post = DB::table('posts')->where(['id'=>$postid, 'hide'=>0])->first();
if($user && $post && in_array($vote, [0,1,-1])){
DB::table('votes')
->updateOrInsert(['user_id'=>$userid, 'post_id'=>$postid],[
'user_id' => $userid,
'post_id' => $postid,
'vote' => $vote,
'hide' => 0,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
]);
return ['message'=>'ok'];
}
return abort(403, 'Invalid request');
}