[英]Laravel 5.3 get belongsToMany and count pivot
我有下一个型号:
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 - 数据透视表具有结构:id,poll_id,participant_id。 我需要查看下表:
№|participant.name|Count vote| 1|Mike |15 | 2|................|10 | ..............................
计数投票获得数据透视表poll_results。 请帮忙,写一下查询。
$poll = Polling::first();
$poll->participants()->get();
您可能想要使用withCount()
方法。
如果您想要计算关系中的结果数而不实际加载它们,您可以使用withCount方法,该方法会在结果模型上放置{relation} _count列
您的查询将如下所示:
Participant::withCount('polls')->get();
这会将新属性添加到名为polls_count
结果中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.