There is a relative database

- Названия категорий - Списки категорий 

I deduce the names and categories as follows:

 $cat_name = DB::table('cat_name')->get(); foreach($cat_name as $row) { $child = DB::table('categories')->where('id','=',$row->id)->get(); echo $row->title; foreach($child as $c) { echo $c->title; } } 

I know what I'm doing is wrong, how to display categories correctly?

    1 answer 1

    Use Eloquent models in which you define a relationship between tables. As I understand it, you have here cat_name one-to-many categories .

    Model classes are approximately:

     <?php // Cat_name.php namespace App; use Illuminate\Database\Eloquent\Model; class Cat_name extends Model { public function categories(){ return $this->hasMany('App\Category'); } } 

    and the second model:

     <?php // Category.php namespace App; use Illuminate\Database\Eloquent\Model; class Category extends Model { } 

    And the conclusion:

     <?php $cat_name = Cat_name::with('categories')->all(); foreach($cat_name as $name) { echo $name->title; foreach($name->categories as $c) { echo $c->title; } } 
    • here is the nesting level 2. and how to repeat a similar trick for nesting 3? - asd
    • one
      It is possible and deeper. If another relation from categories to, for example, metadata is also specified, but in the categories model: public function meta(){ return $this->hasMany('App\Metadata');} , then add the path through the points to the query : ->with('categories.meta') and cycle through $c->meta - Sergiks