public function recommendedArticle($id) { return RecommendArticle::where(['user_id' => \Auth::user()->id, 'article_id' => $id])->first(); }
public function recommendArticle(Request $request) { $record = RecommendArticle::where(['user_id' => \Auth::user()->id, 'article_id' => $request->get('id')])->first(); $article = Article::findOrFail($request->get('id')); if ($record) { //表示已经推荐过该文章,则需要在recommend_articles表中删除该记录,同时article表recommend字段自减 $result1 = RecommendArticle::where(['user_id' => \Auth::user()->id, 'article_id' => $request->get('id')])->delete(); if ($result1) { $result2 = Article::where('id', $request->get('id'))->decrement('recommend'); if ($result2) { //false表示自减 $this->setFlag(false); $this->succeed(true); } else { $this->setResult("article表recommend字段自减操作失败!"); $this->fail(true); } } else { $this->setResult("like_articles表删除记录失败!"); $this->fail(true); } } else { //用户不能推荐自己的文章 if ($article->user_id == \Auth::user()->id) { $this->setResult("用户不能推荐自己的文章!"); $this->fail(true); } else { $result1 = RecommendArticle::Create(array('user_id' => \Auth::user()->id, 'article_id' => $request->get('id'))); User::where('id', $article->user_id)->increment('score', 5); if ($result1) { $result2 = Article::where('id', $request->get('id'))->increment('recommend'); if ($result2) { //true表示自增 $this->setFlag(true); $this->succeed(true); } else { $this->setResult("article表recommend字段自增操作失败!"); $this->fail(true); } } else { $this->setResult("like_articles表操作失败!"); $this->fail(true); } } } }