【问题标题】:How to get recursive tables data in laravel如何在laravel中获取递归表数据
【发布时间】:2015-03-03 18:22:08
【问题描述】:

我有三张桌子 Categories, Websites, Categorywebsites

类别表有字段:

id | parent_id | name

网站表有字段:

id | name

Categorywebsites 表有字段:

id | website_id | category_id

我想获取父类别及其子类别及其对应的类别网站,然后获取与单个数组中的类别网站相对应的网站详细信息。

我已经在类别模型中定义了关系

public function categories(){
 return $this->hasMany('Category','parent_id','id');
}

// To get categories website linked to category.
public function categorywebsites(){
    return $this->hasMany('Categorywebsite');
}

public function websites(){
    return $this->belongsToMany('Website');
}

我正在使用此代码获取层次结构中的所有数据但我得到了

Array(
  [0] => Array
    (
        [id] => 1
        [parent_id] => 0
        [cat_name] => Search Engine
        [categories] => Array
            ([0] => Array([id] => 6
                        [parent_id] => 1
                        [cat_name] => PPC
                        [websites] => Array
                            ([0] => Array(
                                        [id] => 1
                                        [website_id] => 1
                                        [category_id] => 6
                                    )[1] => Array
                                    ([id] => 2
                                     [website_id] => 2
                                     [category_id] => 6
                                   )[2] => Array
                                    (
                                        [id] => 3
                                        [website_id] => 3
                                        [category_id] => 6
                                    )
                                  )
                                )   

首先,我的动机也是使用categrywebsites 子数组获取网站详细信息。我想使用一个查询来获取数据。这个过程会使系统变慢。

感谢任何帮助

提前致谢

【问题讨论】:

    标签: php laravel frameworks


    【解决方案1】:

    如果对你的数据库的读取动作很慢,只需在你的sql语句中添加->remember(5),其中5表示记住选择结果5分钟。当然,假设您的类别内容不会不断变化。缓存内容将显着提高性能。

    至于你的其他问题,我不明白你想要什么。也许您可以粘贴您想要的子数组,这样我就可以帮助您构造确切的sql语句。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-17
      • 2022-12-12
      • 2021-08-04
      • 2018-02-26
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多