php - 如何使用 Eloquent 从中间表中获取所有关系?
问题描述
我有很多关系,例如:
// Category Model
class Category extends Model
{
public function sections()
{
return $this->belongsToMany('App\Section');
}
}
// Section Model
class Section extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
假设我与以下 slug 有以下类别/部分关系:
domestic
dogs
cats
birds
zoo
cats
birds
winged
birds
是否有一种雄辩的或简单的方法来列出所有部分及其类别?
为了把它放在上下文中,如果 category 和 section 有一个 slug,基于我的例子,我想得到一个这样的部分列表:
domestic/dogs
domestic/cats
domestic/birds
zoo/cats
zoo/birds
winged/birds
我试图通过扩展 Pivot 类来创建一个 Pivot 模型,但无法解决。
非常感谢任何帮助。
解决方案
像这样的东西可以解决问题:
// Retrieve all categories
$categories = Category::with('sections')->all();
// Define result array
$result = [];
foreach ($categories as $category) {
foreach ($category->sections as $section) {
$result[] = $category->slug . '/' . $section->slug;
}
}
// Result now holds the contents you are looking for
推荐阅读
- c# - 在 WPF 中序列化和反序列化 UserControl 依赖属性
- azure - 如何在不停止 VM 的情况下更改 VM 公共 IP 地址
- reactjs - 更新使用 firebase 托管的 react 项目
- javascript - load 函数不加载新内容
- python - 如何解析numpy数组python中的数据点?
- python - 按时间箱/间隔计算并发用户会话
- javascript - 即使使用时区设置,两个日期之间的时间差也会返回错误
- google-sheets - 当行被移动并且上面的行发生变化时在上面添加列
- r - 如何在r中为回归线上方和下方的ggplot点着色?
- python - 尽管 Big-O 相同,为什么这两个函数的性能差异如此之大?