如何在laravel中编写此查询

时间:2018-10-15 07:07:45

标签: mysql laravel

我有两个桌子

1. menu

id      -     menu_name    -     menu_url
1       -     Home         -      index
2       -     About        -      about
3       -     Services     -            
4       -     Contact      -      contact

2. submenu 

id      -     menu_name    -     submenu_name  
1       -     Services     -      Web Development
2       -     Services     -      Web Designing
3       -     Services     -      Logo Designing      
4       -     Services     -      SEO

为此,我已经在php中创建了此查询

$query = mysqli_query($con,"SELECT * FROM menu");
while ($row = mysqli_fetch_assoc($query)){
      if ($row['menu_url'] == ''){
        $subquery = mysqli_query($con,"SELECT * FROM submenu WHERE 
        menu_name = '".$row['menu_name']."'");
          while ($row1 = mysqli_fetch_assoc($subquery)){
            //do something here
           }
        }else{
           //do something here
        }
}

我的问题是我该如何在laravel中执行此查询?

我的控制器查询

$menu = menu::all();

$submenu = submenu::where('menu_name','i want the $menu->menu_name variable here')->get();

如何在第二次查询中获取该变量。

在此先感谢您的帮助。

5 个答案:

答案 0 :(得分:1)

一种更有效的方法:

$all_sub_menu = Submenu::get();

$all_sub_menu = collect($all_sub_menu)->groupBy('menu_name');

foreach( $menu as $m )  // To get the individual records
{

    if(isset($all_sub_menu[$m->menu_name]){
        $sub_menu = $all_sub_menu[$m->menu_name]; 
        // you will get submenu for the current menu without requesting the database again and again
    }
    else{
        $sub_menu = array();
    }
}

答案 1 :(得分:0)

尝试一下:

$menu=menu::all();

if( count( $menu ) > 0 )  // Iterate only when there is some data available
{
    foreach( $menu as $m )  // To get the individual records
    {
        $submenu=submenu::where('menu_name', $m->menu_name)->get();

        // here $submenu is an Std Class object, so use foreach() in the same way as above
    }
}

PS::在循环中进行查询不是一个好主意。

答案 2 :(得分:0)

尝试以下代码:

数字1:

$menu=menu::all();

$menu->each(
    function($eachMenu)
    {
        $submenu[] = submenu::where('menu_name', $eachMenu->menu_name)->get();
    }
)

数字2:

$menu=menu::all();

foreach($menu as $eachMenu) {
    $submenu[] = submenu::where('menu_name', $eachMenu->menu_name)->get();
}

答案 3 :(得分:0)

我认为,如果在MenuSubmenu模型之间建立一对多关系会更好,为此,如果您提供外键{{1} } menu_id表中;

因此,您将有两个带有以下列的表:

sumbenu

可以在每个模型中定义关系之后

菜单型号:

menu{id(primary_key), menu_name, menu_url(better to provide slug not url)};
sumenu{id(primary_key), menu_id(foreign_key pointing to menu tables id), sumbenu_name, submenu_url(better to provide slug not url)}

子菜单模型:

public function submenus()
    {
        return $this->hasMany('App\SubMenu');
    }

毕竟您可以做public function menu() { return $this->belongsTo('App\Menu'); } ,然后将$ menus变量传递到前端视图,在前端可以编写

$menuitems = Menu::all()

就这样:)

答案 4 :(得分:0)

您的第一个查询(和循环)是不必要的:

SELECT x.* 
  FROM submenu x
  JOIN menu y
    ON y.menu_name = x.menu_name;

我将把laravel留给读者练习

此外,正如其他人所提到的,您应该将菜单表的PK用作子菜单表的FK。