关系表上的Laravel 5.1总和

时间:2016-08-15 19:41:25

标签: php mysql laravel

我有以下表格:

Schema::create('bc_blueprint', function (Blueprint $table) {
    $table->increments('id');
    $table->string('user_id')->unsiged();
    $table->string('name', 50);
    $table->string('author_name', 50);
    $table->string('bc_version', 50);
    $table->string('version', 10);
    $table->string('archive_name', 50);
    $table->string('screenshot', 50);
    $table->string('screenshot_optional_0', 50)->nullable();
    $table->string('screenshot_optional_1', 50)->nullable();
    $table->tinyInteger('survival_creative');
    $table->tinyInteger('sizeZ');
    $table->tinyInteger('sizeY');
    $table->tinyInteger('sizeX');
    $table->text('description');
    $table->timestamp('uploaded_at');
});

Schema::create('bc_vote', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->integer('blueprint_id')->unsigned();
    $table->tinyInteger('vote')->unsigned();

    $table
        ->foreign('blueprint_id')
        ->references('id')
        ->on('bc_blueprint')
        ->onDelete('cascade')
        ->onUpdate('cascade');
});

我正试图通过关系获取sum表中的vote bc_vote字段。

bc_blueprint表与bc_vote表具有以下关系;

public function hasManyBlueprintVote()
{
    return $this->hasMany(BlueprintVote::class, 'blueprint_id', 'id');
}

bc_vote有:

public function belongsToBlueprint()
{
    return $this->belongsTo(Blueprint::class, 'id', 'blueprint_id');
}

到目前为止我已经尝试过了:

public function browseSingles(Blueprint $blueprint)
{
    $buildcraftSingles = $blueprint->with([
        'hasManyBlueprintVote' => function ($query)
        {
            $query->select(\DB::raw('sum(vote) as total_votes'));
        }
    ])
        ->get();

哪个不起作用(至少我认为应该如此)。

我尝试在bc_blueprint模型中做同样的事情:

public function hasManyBlueprintVoteTotal() {
    return $this->hasMany(BlueprintVote::class)
        ->select(\DB::raw('sum(bc_vote.vote) as votes'));
}

再也没有。也许我误解了我应该怎么做。

任何指向正确方向的人都会受到赞赏。

回答我自己的问题。我放弃了尝试用关系做的事情,然后继续循环并将它们添加到PHP中:

$buildcraftSingles
    ->pluck('hasManyBlueprintVote')
    ->map(function ($item, $value)
    {
        $item['total_votes'] = $item->sum('vote');
    });

0 个答案:

没有答案