【问题标题】:retrive data (count , etc(user data ) ) from pivot table laravel从数据透视表 laravel 中检索数据(计数等(用户数据))
【发布时间】: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);
}

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    您可以使用php artisan make:resource AskResource 为获取的数据创建资源,并使用count() 函数获取数据长度。

    【讨论】:

    • 它不是关于 api / 我的问题是关于 realtions
    猜你喜欢
    • 2015-01-27
    • 1970-01-01
    • 2020-04-06
    • 2021-01-22
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 2018-04-10
    • 2021-09-24
    相关资源
    最近更新 更多