我想要判断某个评论的user_id是不是这篇文章的user_id,“文章”及“评论”的模型和控制文件应该如何修改?
想要的效果:
我想要在一个“评论”的视图文件中,判断某个评论的user_id是不是这篇文章的user_id,但我自己无论怎么尝试,都无法获取$article->user_id的数据,诚心请教各位:“文章”及“评论”的模型和控制文件应该如何修改?
1. “评论”的视图文件:item.blade.php
<div class="media-heading">
<a href="{{ route('auth.space.index',['user_id'=>$comment->user->id]) }}" target="_blank">{{ $comment->user->name }} @if($comment->user->authentication && $comment->user->authentication->status === 1)<span class="text-yellow"><i class="iconfont icon-vip-o" aria-hidden="true" data-toggle="tooltip" data-placement="right" title="" data-original-title="已通过达人认证"></i></span>@endif</a>
@foreach($articles as $article)
@if($source_type === 'article' && $comment->user_id === $article->user_id)
<span class="label-xs label-success">作者</span>
@endif
@endforeach
@if($comment->to_user_id)
<span class="text-muted"> • 回复 • </span>
<a href="{{ route('auth.space.index',['user_id'=>$comment->to_user_id]) }}" target="_blank">{{ $comment->toUser->name }} @if($comment->toUser->authentication && $comment->toUser->authentication->status === 1)<span class="text-yellow"><i class="iconfont icon-vip-o" aria-hidden="true" data-toggle="tooltip" data-placement="right" title="" data-original-title="已通过达人认证"></i></span>@endif</a>
@endif
</div>
2. 模型文件:
1). “评论”的模型文件:Comment.php
<?php
namespace App\Models;
use App\Models\Relations\BelongsToUserTrait;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use BelongsToUserTrait;
protected $table = 'comments';
protected $fillable = ['user_id', 'content','source_id','source_type','to_user_id','supports','device','status'];
public static function boot()
{
parent::boot();
/*监听创建*/
static::creating(function($comment){
/*开启状态检查*/
if(Setting()->get('verify_comment')==1){
$comment->status = 0;
}
});
/*监听删除事件*/
static::deleting(function($comment){
/*问题、回答、文章评论数 -1*/
$comment->source()->where("comments",">",0)->decrement('comments');
});
}
public function source()
{
return $this->morphTo();
}
public function toUser(){
return $this->belongsTo('App\Models\User','to_user_id');
}
}
2). “文章”的模型文件:Article.php
<?php
namespace App\Models;
use App\Models\Relations\BelongsToCategoryTrait;
use App\Models\Relations\BelongsToUserTrait;
use App\Models\Relations\MorphManyCommentsTrait;
use App\Models\Relations\MorphManyTagsTrait;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;
class Article extends Model
{
use BelongsToUserTrait,MorphManyTagsTrait,MorphManyCommentsTrait,BelongsToCategoryTrait;
protected $table = 'articles';
protected $fillable = ['title', 'user_id','category_id', 'content','tags','summary','status','logo'];
public function getUpdatedAtColumn() {
return null;
}
public static function boot()
{
parent::boot();
/*监听创建*/
static::creating(function($article){
/*开启状态检查*/
if(Setting()->get('verify_article')==1){
$article->status = 0;
}
if( trim($article->summary) === '' ){
$article->summary = str_limit(strip_tags($article->content),180);
}
});
static::saved(function($article){
if(Setting()->get('xunsearch_open',0) == 1){
App::offsetGet('search')->update($article);
}
});
/*监听删除事件*/
static::deleting(function($article){
/*用户文章数 -1 */
$article->user->userData()->where("articles",">",0)->decrement('articles');
Collection::where('source_type','=',get_class($article))->where('source_id','=',$article->id)->delete();
/*删除文章评论*/
Comment::where('source_type','=',get_class($article))->where('source_id','=',$article->id)->delete();
/*删除动态*/
Doing::where('source_type','=',get_class($article))->where('source_id','=',$article->id)->delete();
});
static::deleted(function($article){
if(Setting()->get('xunsearch_open',0) == 1){
App::offsetGet('search')->delete($article);
}
});
}
/*获取相关文章*/
public static function correlations($tagIds,$size=10)
{
$articles = self::where("status",">",0)->whereHas('tags', function ($query) use ($tagIds) {
$query->whereIn('tag_id', $tagIds);
})->orderBy('created_at','DESC')->take($size)->get();
return $articles;
}
/*搜索*/
public static function search($word,$size=20)
{
$list = self::where('title','like',"$word%")->paginate($size);
return $list;
}
/*推荐文章*/
public static function recommended($categoryId=0 , $pageSize=20)
{
$query = self::query();
$category = Category::findFromCache($categoryId);
if( $category ){
$query->whereIn('category_id',$category->getSubIds());
}
if(Setting()->get('hot_content_period',365)){
$query->where('created_at', ">" , Carbon::now()->subDays(Setting()->get('hot_content_period',365)));
}
$list = $query->where('status','>',0)->orderBy('supports','DESC')->orderBy('created_at','DESC')->paginate($pageSize);
return $list;
}
/*热门文章*/
public static function hottest($categoryId=0 , $pageSize=20)
{
$query = self::query();
$category = Category::findFromCache($categoryId);
if( $category ){
$query->whereIn('category_id',$category->getSubIds());
}
if(Setting()->get('hot_content_period',365)){
$query->where('created_at', ">" , Carbon::now()->subDays(Setting()->get('hot_content_period',365)));
}
$list = $query->where('status','>',0)->orderBy('comments','DESC')->orderBy('views','DESC')->orderBy('created_at','DESC')->paginate($pageSize);
return $list;
}
/*最新文章*/
public static function newest($categoryId=0 , $pageSize=20)
{
$query = self::query();
$category = Category::findFromCache($categoryId);
if( $category ){
$query->whereIn('category_id',$category->getSubIds());
}
$list = $query->where('status','>',0)->orderBy('updated_at','DESC')->paginate($pageSize);
return $list;
}
}
3. 控制文件:
1). “评论”的控制文件:CommentController.php
<?php
namespace App\Http\Controllers\Ask;
use App\Models\Answer;
use App\Models\Article;
use App\Models\Comment;
use App\Models\Question;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CommentController extends Controller
{
/*问题创建校验*/
protected $validateRules = [
'content' => 'required|max:10000',
];
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,$this->validateRules);
$source_type = $request->input('source_type');
$source_id = $request->input('source_id');
if($source_type === 'question'){
$source = Question::find($source_id);
$notify_subject = $source->title;
$notify_type = 'comment_question';
$notify_refer_type = 'question';
$notify_refer_id = 0;
}else if($source_type === 'answer'){
$source = Answer::find($source_id);
$notify_subject = $source->content;
$notify_type = 'comment_answer';
$notify_refer_type = 'answer';
$notify_refer_id = $source->question_id;
}else if($source_type === 'article'){
$source = Article::find($source_id);
$notify_subject = $source->title;
$notify_type = 'comment_article';
$notify_refer_type = 'article';
$notify_refer_id = 0;
}
if(!$source){
abort(404);
}
$data = [
'user_id' => $request->user()->id,
'content' => $request->input('content'),
'source_id' => $source_id,
'source_type' => get_class($source),
'to_user_id' => $request->input('to_user_id'),
'status' => 1,
'supports' => 0
];
$comment = Comment::create($data);
/*问题、回答、文章评论数+1*/
$comment->source()->increment('comments', 1, ['updated_at' => $comment->freshTimestamp()]);
if( $comment->to_user_id > 0 ){
$this->notify($request->user()->id,$comment->to_user_id,'reply_comment',$notify_subject,$source_id,$comment->content,$notify_refer_type,$notify_refer_id);
}else{
$this->notify($request->user()->id,$source->user_id,$notify_type,$notify_subject,$source_id,$comment->content,$notify_refer_type,$notify_refer_id);
}
return view('theme::comment.item')->with('comment',$comment)
->with('source_type',$source_type)
->with('source_id',$source_id);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($source_type,$source_id)
{
if($source_type === 'question'){
$source = Question::find($source_id);
}else if($source_type === 'answer'){
$source = Answer::find($source_id);
}else if($source_type === 'article'){
$source = Article::find($source_id);
}
if(!$source){
abort(404);
}
$comments = $source->comments()->orderBy('supports','desc')->orderBy('created_at','asc')->simplePaginate(15);
return view('theme::comment.paginate')->with('comments',$comments)
->with('source_type',$source_type)
->with('source_id',$source_id);
}
}
2). “文章”的控制文件:ArticleController.php
<?php
namespace App\Http\Controllers\Blog;
use App\Models\Article;
use App\Models\Draft;
use App\Models\Question;
use App\Models\Tag;
use App\Models\UserData;
use App\Models\UserTag;
use App\Services\CaptchaService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Storage;
class ArticleController extends Controller
{
/*问题创建校验*/
protected $validateRules = [
'title' => 'required|min:5|max:255',
'content' => 'required|min:50|max:16777215',
'summary' => 'sometimes|max:255',
'tags' => 'sometimes|max:128',
'category_id' => 'sometimes|numeric'
];
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$draftId = $request->query('draftId', '');
$draft = Draft::find($draftId);
if ($draftId && !$draft) {
abort(404);
}
$formData = [];
$formData['subject'] = '';
$formData['content'] = '';
$formData['category_id'] = 0;
if($draft){
$draft->form_data = json_decode($draft->form_data,true);
$formData['subject'] = $draft->subject;
$formData['content'] = $draft->editor_content;
$formData['category_id'] = $draft->form_data['category_id'];
}
return view("theme::article.create")->with(compact('formData'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request, CaptchaService $captchaService)
{
$loginUser = $request->user();
if($request->user()->status === 0){
return $this->error(route('website.index'),'操作失败!您的邮箱还未验证,验证后才能进行该操作!');
}
/*防灌水检查*/
if( Setting()->get('article_limit_num') > 0 ){
$questionCount = $this->counter('article_num_'. $loginUser->id);
if( $questionCount > Setting()->get('article_limit_num')){
return $this->showErrorMsg(route('website.index'),'您已超过每小时文章发表限制数'.Setting()->get('article_limit_num').',请稍后再进行该操作,如有疑问请联系管理员!');
}
}
$request->flash();
/*如果开启验证码则需要输入验证码*/
if( Setting()->get('code_create_article') ){
$captchaService->setValidateRules('code_create_article',$this->validateRules);
}
$this->validate($request,$this->validateRules);
$data = [
'user_id' => $loginUser->id,
'category_id' => intval($request->input('category_id',0)),
'title' => trim($request->input('title')),
'content' => clean($request->input('content')),
'summary' => $request->input('summary'),
'status' => 1,
];
if($request->hasFile('logo')){
$validateRules = [
'logo' => 'required|image|max:'.config('tipask.upload.image_size'),
];
$this->validate($request,$validateRules);
$file = $request->file('logo');
$extension = $file->getClientOriginalExtension();
$filePath = 'articles/'.gmdate("Y")."/".gmdate("m")."/".uniqid(str_random(8)).'.'.$extension;
Storage::disk('local')->put($filePath,File::get($file));
$data['logo'] = str_replace("/","-",$filePath);
}
$article = Article::create($data);
/*判断问题是否添加成功*/
if($article){
/*添加标签*/
$tagString = trim($request->input('tags'));
Tag::multiSave($tagString,$article);
//记录动态
$this->doing($article->user_id,'create_article',get_class($article),$article->id,$article->title,$article->summary);
/*用户提问数+1*/
$loginUser->userData()->increment('articles');
UserTag::multiIncrement($loginUser->id,$article->tags()->get(),'articles');
if($article->status === 1 ){
$this->credit($request->user()->id,'create_article',Setting()->get('coins_write_article'),Setting()->get('credits_write_article'),$article->id,$article->title);
$message = '文章发布成功! '.get_credit_message(Setting()->get('credits_write_article'),Setting()->get('coins_write_article'));
}else{
$message = '文章发布成功!为了确保文章的质量,我们会对您发布的文章进行审核。请耐心等待......';
}
$this->counter( 'article_num_'. $article->user_id , 1 , 60 );
return $this->success(route('blog.article.detail',['id'=>$article->id]),$message);
}
return $this->error("文章发布失败,请稍后再试",route('website.index'));
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id,Request $request)
{
$article = Article::findOrFail($id);
/*待审核文章游客不可见,管理员和内容作者可见*/
if($article->status == 0){
if(Auth()->guest()){
abort(404);
}
$this->authorize('create',$article);
}
/*文章查看数+1*/
$article->increment('views');
$topUsers = Cache::remember('article_top_article_users',10,function() {
return UserData::top('articles',8);
});
/*相关问题*/
$relatedQuestions = Question::correlations($article->tags()->pluck('tag_id'));
/*相关文章*/
$relatedArticles = Article::correlations($article->tags()->pluck('tag_id'));
/*设置通知为已读*/
if($request->user()){
$this->readNotifications($article->id,'article');
}
return view("theme::article.show")->with('article',$article)
->with('topUsers',$topUsers)
->with('relatedQuestions',$relatedQuestions)
->with('relatedArticles',$relatedArticles);
}
/**
* 显示文字编辑页面
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id,Request $request)
{
$article = Article::find($id);
if(!$article){
abort(404);
}
/*编辑权限控制*/
$this->authorize('update', $article);
/*编辑问题时效控制*/
if(!Gate::allows('updateInTime',$article)){
return $this->showErrorMsg(route('website.index'),'您已超过文章可编辑的最大时长,不能进行编辑了。如有疑问请联系管理员!');
}
return view("theme::article.edit")->with(compact('article'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request,CaptchaService $captchaService)
{
$article_id = $request->input('id');
$article = Article::find($article_id);
if(!$article){
abort(404);
}
$this->authorize('update', $article);
$request->flash();
/*如果开启验证码则需要输入验证码*/
if( Setting()->get('code_create_article') ){
$captchaService->setValidateRules('code_create_article', $this->validateRules);
}
$this->validate($request,$this->validateRules);
$article->title = trim($request->input('title'));
$article->content = clean($request->input('content'));
$article->summary = $request->input('summary');
$article->category_id = $request->input('category_id',0);
if($request->hasFile('logo')){
$validateRules = [
'logo' => 'required|image|max:'.config('tipask.upload.image_size'),
];
$this->validate($request,$validateRules);
$file = $request->file('logo');
$extension = $file->getClientOriginalExtension();
$filePath = 'articles/'.gmdate("Y")."/".gmdate("m")."/".uniqid(str_random(8)).'.'.$extension;
Storage::disk('local')->put($filePath,File::get($file));
$article->logo = str_replace("/","-",$filePath);
}
$article->save();
$tagString = trim($request->input('tags'));
/*更新标签*/
Tag::multiSave($tagString,$article);
return $this->success(route('blog.article.detail',['id'=>$article->id]),"文章编辑成功");
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
试试不用全等? 用==?