我可以将数据透视表数据合并到父对象中吗?

时间:2020-11-11 00:57:01

标签: laravel

我有两个模型,CategoryItem通过数据透视表连接。

数据透视表category_item有一个名为position的列。在类别模型上,我急于加载Items。我想知道是否可以设置模型,以便在每次调用Item时,都会自动将position属性附加到自身。

例如,如果我运行App\Models\Category::find(1)->items()->get()之类的东西,并且返回该类别及其关联的商品,我希望这些商品中的每一个也都具有Position属性(位于数据透视表)。这可能吗?

Category.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Category extends Model
{
    protected $fillable = [
        'name'
    ];

    // automatically eager load items of a category
    protected $with = ['items'];

    // define relationships
    public function items(): BelongsToMany
    {
        return $this
            ->belongsToMany('App\Models\Item')
            ->withPivot('position')
            ->withTimestamps();
    }
}

Item.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Item extends Model
{
    protected $fillable = [
        'name', 'category_id', 'quantity'
    ];

    // define relationships
    public function categories(): BelongsToMany
    {
        return $this
            ->belongsToMany('App\Models\Category')
            ->withPivot('position')
            ->withTimestamps();
    }
}

1 个答案:

答案 0 :(得分:1)

尝试:

在您的类别模型中:

public function items(): BelongsToMany
{
    return $this
        ->belongsToMany('App\Models\Item')
        ->select('items.*', 'category_item.position as position');
}

现在:

App\Models\Category::with('items')->find(1);

应该给您带有项目的类别以及项目的位置。

尝试一下,让我知道。