I have two tables
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
for that i have created this query in 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
}
}
my question is that how do i do this query in laravel ?
my controller query
$menu = menu::all();
$submenu = submenu::where('menu_name','i want the $menu->menu_name variable here')->get();
how to get that variable in second query.
Thanks in advance any help will be appreciated.
5
Answers
Try this:
P.S.: Querying inside a loop is not a good idea.
A more efficient way:
Try below codes :
number 1 :
number 2:
I think it would be better if you create one-to-many relationship between
Menu
andSubmenu
models, in order to do this it would be better if you provide Foreign Keymenu_id
insumbenu
table;So you will have two tables with following columns:
After you can define relationships in each model
Menu Model:
SubMenu Model:
after all you can do
$menuitems = Menu::all()
, then pass the $menus variable to frontend view, and in frontend you can writeThat’s it 🙂
Your first query (and loop) are unnecessary:
I’ll leave the laravel bit as an exercise for the reader
Also, as mentioned by others, you should use the PK of the menu table as the FK of the submenu table.