Laravel 自关系多对多

Ran*_*all 2 laravel

我有桌子items(意味着人工制品)。并且可以使用另一个(一个或多个)人工制品来创建人工制品(不是全部)。

我在 google 中找不到任何工作示例如何在 laravel 中进行多对多自关系。

我写了这样的东西:

class Item extends Model
{
    public function items()
    {
        return $this->belongsToMany('App\Item', 'item_id');
    }

    public function components()
    {
        return $this->belongsToMany('App\Item', 'component_id');
    }
}
Run Code Online (Sandbox Code Playgroud)

但我不知道下一步该做什么。我卡住了。任何帮助将不胜感激。

这是我的表结构:

id | name | price | extra_item_slot
------------------------------------
Run Code Online (Sandbox Code Playgroud)

但如果需要,我可以更改它。添加另一列或类似的内容。

更新:一个 Artefact 可以包含多个子 Artefact。

unc*_*exo 6

正如你所要求的一个例子

这个答案只是为了给您提供一个与同一张表的多对多关系的例子。这实际上称为自引用表。那么让我们开始吧。

首先,我们需要创建两个表。一个用于工件名称,另一个是中间表,称为数据透视表。这里的parent_child表是一个数据透视表。

Schema::create('artifacts', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('parent_child', function (Blueprint $table) {
    $table->unsignedInteger('parent_id');
    $table->foreign('parent_id')
        ->references('id')
        ->on('artifacts');

    $table->unsignedInteger('child_id')->nullable();
    $table->foreign('child_id')
        ->references('id')
        ->on('artifacts');

    $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

现在我们需要为这两个表设置种子。为了简洁起见,我将把它们放入链接中。这里是ArtifactSeeder.phpParentChildSeeder.php

接下来,我们需要告诉模型建立多对多的自引用关系。这是我们的模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Artifact extends Model
{
    public function children()
    {
        return $this->belongsToMany(
            Artifact::class,
            'parent_child',
            'parent_id',
            'child_id'
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

现在是时候处理数据了。那么让我们来玩一下吧。

$parent = Artifact::where('name', '=', 'D')->first();

// or 

$parent = Artifact::find(2);

foreach ($parent->children as $child) {
    echo $child->name . '<br>';
}
Run Code Online (Sandbox Code Playgroud)

我认为在你的情况下没有必要使用多对多关系。您可以使用一对多关系获取预期数据,如@ZhengYu的答案。不过,您可以探索任何您想要的内容。谢谢!:)