R
R
root092018-10-27 20:41:27
Laravel
root09, 2018-10-27 20:41:27

How to get a list of all users who wrote a comment on an article?

How to get a list of all users who wrote a comment on an article?
Now implemented like this:

$list = Comment::where('article_id', 1)->get()->load('user');
$users = $list->map(function($list){
     return $list->user;
})->unique();

But I think the method is more optimized?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor Evgeniev, 2018-10-27
@root09

First, the database structure:

Comment (article_id, id, text, user_id)
Article (id, text, user_id)
User (id, name)

Models now:
Article.php
public function comments(){
return $this->hasMany(Comment::class);
}
public function author(){
return $this->belongsTo(User::class);
}
public function commetators(){
return $this->hasManyThrough(User::class, Comment::class);

Comment.php
public function article(){
return $this->belongsTo(Article::class);
}
public function user(){
return $this->belongsTo(User::class);
}

Code to search for all users who wrote comments on the article.
$users = Article::find(1)->commentators;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question