gpt4 book ai didi

mysql - Laravel 中单表的数据透视表

转载 作者:行者123 更新时间:2023-11-29 06:31:18 25 4
gpt4 key购买 nike

我正在尝试在我的网站中添加多级类别。其中一个类别可以有多个子级,也可以有多个父级。它看起来像 Laravel 中的多对多关系,我必须使用数据透视表。

这样我就创建了一个名为categories的表和一个数据透视表categories_reltionship,如下所示。现在我的问题是如何与 Laravel 中的这张表建立多对多关系。

categories table
==================
id title
=== ======
1 title_1
2 title_2
3 title_3
4 title_4
5 title_5
categories_relationship table
==================
parent_id child_id
========== ======
1 2
1 3
4 2
4 3
5 2
5 3

最佳答案

您可以在 Category 模型上使用如下方法:

//This will get you the list of categories
public function categories()
{
return ($this->hasManyThrough('App\Models\Category', 'App\Models\CategoryRelation', 'child_id', 'id', 'id', 'parent_id'));
}

//This will get you the list of children
public function childs()
{
return ($this->hasManyThrough('App\Models\Category', 'App\Models\CategoryRelation', 'parent_id', 'id', 'id', 'child_id'));
}

CategoryRelation模型上:

class CategoryRelation extends Model
{
protected $table = 'categories_relationship';
}

希望这能帮助您解决问题

注意:我建议您为many to many准备3张 table 关系,

关于mysql - Laravel 中单表的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56106830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com