简体   繁体   中英

Loop through two tables in Laravel

Let's say I have two tables. Table 1 is called "rooms" and table 2 is called "fruits". In every room there is a left and a right side and the fruits from table "fruits" are going to be put to the left or right side of the room.

An example: In room "kitchen" we have 2 bananas on the right side and 5 bananas on the left side.

My tables according the example:

room

id name

1 kitchen

2 bedroom

fruits

id | name | 1_right | 1_left | 2_right | 2_left

1 | apple | 0 | 0 | 0 | 0

2 | banana | 2 | 5 | 0 | 0

As you can see "1_right" is "kitchenID_right". In the blade view I would like to loop through my "rooms" with the data from "right" and "left":

Where are bananas?

  • kitchen right: 2
  • kitchen left: 5
  • bedroom right: 0
  • bedroom left: 0

Any ideas on how I can do this with Laravel? Of course, I can do a sql query in the blade view, but since I know that this is bad practice I was wondering if there is a cleaner way to achieve the same result.

If your rooms are fixed, you don't need to create rooms table. Otherwise it's not a good idea to add IDs of room table as field prefix in fruits table. You can not join them in a proper way. You should alter your tables. You can create a 3rd -mapping- table.

eg

room_fruits [table name]
room_id
left_fruit_id
right_fruit_id

You should also use many to many relationship of Eloquent .

First you should re-structure your database as this ..

ROOMS

id , name

** FRUITS **

id , name , left_qty , right_qty , room_id

Then in your MODEL ROOM

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

in your MODEL FRUITS

public function room()
{
    return $this->belongsTo('App\Room');
}

so in controller you can do

$rooms = Room::all();
foreach($rooms as $room)
{
    echo $room->name;
    foreach($room->fruits as $fruit)
    {
        echo $fruit->name . ': (right)' . $fruit->right_qty . ' (left)' . $fruit->left_qty;
    }
}

REFERENCE

Just a slight improvisation of what @Koray Küpe said, you can create the mapping table as follows, but keeping the rooms table as it is (since rooms may not always be fixed):

Table: room_fruits
-------------------
id
room_id (from rooms table)
fruit_id (from fruits table)
left (boolean)
right (boolean)

This way it'll be easier for you to select fruits that are only on either left or right room when building your query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM