如何通过口才获得文章的用户和评论

时间:2019-04-10 02:30:05

标签: php laravel eloquent

有三个数据库表用户,文章和联接表article_users_comments,其中包含评论,评论该文章的用户ID和评论该文章的ID。

我可以通过纯SQL连接实现以下目标,但是我想用Eloquent做到这一点,我认为这很容易,但是现在我有点困惑。

我一直在尝试不同的方法,但是仍然无法正常工作。

// User

class User extends Authenticatable implements MustVerifyEmail,CanResetPassword{

    public function comments()
    {
        return $this->hasMany('App\ArticleComments');
    }

}

// Article

class Article extends Model{


    public function getArticles(){
        $articles = Article::paginate(3);
        return $articles;
    }

    public function getSingleArticle($title){

        $article = Article::where('title','=',$title)->get();
        return $article;
    }

    public function articleComments()
    {

        return $this->hasMany('App\ArticleComments');
    }

}

// ArticleComments

class ArticleComments extends Model{
      protected $table = 'article_users_comments';
    public $timestamps = false;

    public function article()
    {
        return $this->belongsTo('App\Article');
    }

    public function user()
    {
        $this->belongsTo('App\User');
    }

}

// ArticleController(showing only the show method), which passes the data to the certain view 
instantiating the Article Model 

class ArticleController extends Controller{

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($title)
    {
        $removeDashesFromUrl = str_replace('-',' ',$title);
         $am = new Article();
         $data = $am->getSingleArticle($removeDashesFromUrl);
         return view('article',['article'=>$data]);
    }


}

我想获取某篇文章的评论和用户(评论过该文章的用户)。

1 个答案:

答案 0 :(得分:0)

您应在articleCommentsarticle关系中设置外键:

  

口才通过检查关系方法的名称并在方法名称后加上_id来确定默认的外键名称。但是,您可以将自定义键名作为第二个参数传递给belongsTo方法:

商品模型

 public function articleComments()
 {
     return $this->hasMany('App\ArticleComments','commented_article_id');
 }

ArticleComments模型

public function article()
{
    return $this->belongsTo('App\Article','commented_article_id');
}

您可以使用以下关系从文章中获得评论:

$article = Article::find($id);
$article->articleComments; // This will return all comments for the given article

您可以使用foreach循环并从每个注释访问每个属性:

foreach($article->articleComments as $comment)
{
  echo $comment->id;
  echo $comment->user->id;
  echo $comment->user->username;
    .
    .
    .
}

您可以像上面我一样在评论中调用该关系并访问该用户及其任何属性。

有关更多信息:click here.

注意:我强烈建议您将模型名称更改为注释,因为我们不会使用复数形式的模型名称,而总是使用单数形式。