laravel - Laravel 自我关系多对多
问题描述
我有桌子items
(意味着人工制品)。人工制品(不是全部)可以使用另一个(一个或多个)人工制品来创建。
我在谷歌中找不到任何工作示例如何在 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');
}
}
但我不知道下一步该做什么。我卡住了。任何帮助将不胜感激。
这是我的表结构:
id | name | price | extra_item_slot
------------------------------------
但如果需要,我可以更改它。添加另一列或类似的东西。
更新:一个 Artefact 可以包含多个子 Artefacts。
解决方案
正如你所问的一个例子。
这个答案只是为了给你一个同一张表的多对多关系的例子。这实际上称为自引用表。所以让我们去做吧。
首先,我们需要创建两个表。一个用于工件名称,另一个是称为数据透视表的中间表。这里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 Illuminate\Database\Eloquent\Model;
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的答案来获取您的预期数据。不过,您可以探索任何您想要的东西。谢谢!:)
推荐阅读
- java - 如何在java内部循环中生成LinearLayout的副本
- python - 发现 untitest 类三角形警告
- reactjs - 如何从我的 npm 包中的 react 项目中读取文件?
- python - if 语句加上 concat 结果 pandas
- excel - 应用程序定义或对象定义 End(xlDown) 错误
- html - HTML 页脚背景不适合页脚文本
- angular - ionic 5 angular(电容器相机)和nodejs multer中的多张图像上传
- c++ - 即使没有错误,也不会注入 dll 库
- json - 如何在飞镖颤动中将嵌套的json字符串转换为json对象?
- node.js - 我们不能 SEO Mern Stack 应用程序和 reactjs 应用程序吗?