【问题标题】:Laravel 5.3 get belongsToMany and count pivotLaravel 5.3 获取 belongsToMany 并计算枢轴
【发布时间】:2017-04-27 02:44:16
【问题描述】:

我有下一个模型:

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|计票| 1|迈克|15| 2|.......|10 | .........................................

计票获取数据透视表poll_results。 请帮忙,写查询。

$poll = Polling::first();
$poll->participants()->get();

【问题讨论】:

    标签: php laravel eloquent pivot-table has-many


    【解决方案1】:

    您可能想使用withCount() 方法。

    如果您想在不实际加载关系的情况下计算关系结果的数量,您可以使用 withCount 方法,该方法会在结果模型上放置一个 {relation}_count 列

    您的查询将如下所示:

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

    这将为名为@9​​87654324@的结果添加新属性

    【讨论】:

    • 返回参与者计数(获取参与者表)。 Column Count vote - 需要从 poll_results 表中获取。
    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 2019-05-31
    • 2018-08-28
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2018-03-25
    相关资源
    最近更新 更多