dongliang1893 2016-12-12 09:08
浏览 82

Laravel 5.3获得belongsToMany和count pivot

I have next models:

class Polling extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function participants()
    {
        return $this->belongsToMany(Participant::class, 'participant_poll', 'poll_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function results()
    {
        return $this->belongsToMany(Participant::class, 'poll_results', 'poll_id');
    }
}

class Participant extends Model
{
    public function polls()
    {
        return $this->belongsToMany(Polling::class);
    }

    public function results()
    {
        return $this->belongsToMany(Polling::class);
    }

}

poll_results - pivot table have structure: id, poll_id, participant_id. I need view next table:

№|participant.name|Count vote|
1|Mike            |15        |
2|................|10        |
..............................

Count vote get pivot table poll_results. Help please, write query.

$poll = Polling::first();
$poll->participants()->get();
  • 写回答

1条回答 默认 最新

  • douju3911 2016-12-12 09:15
    关注

    You may want to use withCount() method.

    If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models

    Your query would look like this one:

    Participant::withCount('polls')->get();
    

    This will add new property to results called polls_count

    评论

报告相同问题?

悬赏问题

  • ¥20 C# TCP服务端,客户端退出后,不断有数据进来
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?