包括相关模型中的特定列 table

Include specific column from related-models table

使用 Laravel 5.1:给定两个相关模型,UserItem,通过 table Item_User,如何包含来自通过 table、item_count 使用 with 语句?

Item_User table:

查询:

    $userGameProfile = User::with([
        'items' => function($query) use ($profile_id) {
            $query->with(['phrases'])->where('profile_id', '=', $profile_id);
        }])->find($id);

仅向此查询添加 ->select('item_count') returns 个项目计数,而不是相关的项目对象。添加 ->select('*') 可以获得我想要的项目和字段,但会破坏嵌套的 with(['phrases']) 关系,我需要获取项目的相关短语。

我被告知我应该使用 withPivot,但我找不到关于如何使用它的文档或示例。

最好,我想将其添加到关系中,而不是每个查询中。

型号:

User:

public function items()
{
    return $this->belongsToMany(Item::class, 'user_item');
}

Item:

public function users()
{
    return $this->belongsToMany(User::class, 'user_item');
}
public function phrases()
{
    return $this->belongsToMany(Phrase::class, 'item_phrase');
}

Phrase:

public function items()
{
    return $this->belongsToMany(Item::class, 'item_phrase');
}

This article 突出显示如何包含来自 pivot table 的附加信息。

User 模型中,我知道我总是想从 user_items 枢轴 table 中包含 item_count,因此您可以将 withPivot 添加到与 items 的关系:

public function items()
{
    return $this->belongsToMany(Item::class, 'user_item')
        ->withPivot('item_count');
}

User 现在返回 items 和数据透视表: