我有表格items
(表示人工制品(。工件(不是全部(可以使用另一个(一个或多个(工件创建。
我在谷歌中找不到任何工作示例,如何在 laravel 中进行多对多的自我关系。
我写了这样的东西:
class Item extends Model
{
public function items()
{
return $this->belongsToMany('AppItem', 'item_id');
}
public function components()
{
return $this->belongsToMany('AppItem', 'component_id');
}
}
但我不知道下一步该怎么做。我愣住了。任何帮助将不胜感激。
这是我的表结构:
id | name | price | extra_item_slot
------------------------------------
但是如果需要,我可以更改它。添加另一列或类似的东西。
更新:一个项目可以包含多个子项目。
正如你要求的例子。
此答案仅用于为您提供与同一表的多对多关系的示例。这实际上称为自引用表。所以让我们去做吧。
首先,我们需要创建两个表。一个用于工件名称,另一个是称为数据透视表的中间表。在这里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();
});
现在我们需要为这两个表播种。为简洁起见,我将把它们放在链接中。以下是ArtifactSeeder.php和ParentChildSeeder.php
接下来,我们需要告诉模型构建多对多自引用关系。这是我们的模型:
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Artifact extends Model
{
public function children()
{
return $this->belongsToMany(
Artifact::class,
'parent_child',
'parent_id',
'child_id'
);
}
}
现在是时候处理数据了。所以让我们玩一下。
$parent = Artifact::where('name', '=', 'D')->first();
// or
$parent = Artifact::find(2);
foreach ($parent->children as $child) {
echo $child->name . '<br>';
}
我认为没有必要在您的情况下使用多对多关系。您可以使用一对多关系作为@ZhengYu的答案来获取预期数据。不过,您可以探索任何您想要的东西。谢谢!:)
您可以使用父 ID 保存子工件。 因此,可以使用相同的父 ID 保存子项 1 和子项 2。 例如
id | name | price | extra_item_slot | parent_id
------------------------------------------------
1 parent 10 some 0
2 child1 2 some 1
3 child2 3 some 1
在上面的示例中,项目 1 有 2 个子项 - 项目 2 和项目 3
在这种情况下,您可以在 laravel 中定义多对多关系:
class Item extends Model
{
protected $table = 'item';
public $fillable = ['name', 'price', 'extra_item_slot', 'parent_id'];
public function children() {
return $this->hasMany('AppModelsItem','parent_id','id');
}
}
然后,您可以按照自己的想法获得儿童物品:
$parentItem = Item::where('name', '=', "someword")->where('parent_id', '=', "0")->first();
$childrenItems = $parentItem->children; // you can get all children here
希望对您有所帮助!