【发布时间】:2021-11-07 10:51:24
【问题描述】:
我有下表,我想检索喜欢评论的用户的每条评论的数量(比如 Instagram 评论,任何人都可以喜欢其他用户 cmets)
| users table |
|---|
| id |
| name |
| Asks table |
|---|
| id |
| title |
| comments table |
|---|
| id |
| ask_id |
| user_id |
| text |
| comment_like table |
|---|
| id |
| comment_id |
| user_id |
它用于保存评论链接,它看起来像Instagram评论,任何用户都可以喜欢另一个用户的评论。
这是我的用户模型代码:
class User extends Authenticatable
{
public function comments_like()
{
return $this->belongsToMany(
Comment::class,
'comment_like' ,
'user_id' ,
'comment_id' ,
'id',
'id'
);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
这是我的询问模型代码:
class Ask extends Model
{
use HasFactory;
protected $table = 'asks';
protected $fillable = ['title'];
public function comments()
{
return $this->hasMany(Comment::class);
}
}
这是我的用户模型代码:
class User extends Authenticatable
{
public function comments_like()
{
return $this->belongsToMany(
Comment::class,
'comment_like' ,
'user_id' ,
'comment_id' ,
'id',
'id'
);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
这是我的评论模型代码:
class Comment extends Model
{
//user relation
public function user()
{
return $this->belongsTo(User::class);
}
//ask relation
public function ask()
{
return $this->belongsTo(Ask::class);
}
//comment_like relation
public function users_like ()
{
return $this->belongsToMany(
User::class ,
'comment_like',
'comment_id',
'user_id',
'id',
'id'
)
->withTimestamps();
}
//condition on comment_like relation
public function user_like_byId($id)
{
return $this->belongsToMany(
User::class ,
'comment_like',
'comment_id',
'user_id',
'id',
'id'
)
->where('id',$id)->get();
}
}
我想用他们的 cmets 检索最新的询问,其中包括 comment_like 的计数和数据**
我使用了这段代码,但它显示错误
$ask= Ask::query()->latest('id')->get()->first();
foreach ($ask->comments()->get() as $commentItem) {
echo "id: ".$commentItem->id .'<br>';
echo "name :" .$commentItem->user()->pluck('name')[0] . "<br>";
echo "text :" .$commentItem->text . "<br>";
echo $commentItem->user_like_byId($commentItem->id);
}
【问题讨论】: