#laravel #eloquent
#laravel #красноречивый
Вопрос:
Сегодня я сталкиваюсь с очень странным поведением в Laravel при извлечении записей из таблицы. У меня есть таблица, которая имеет отношение «Один ко многим» к самой себе. Элемент меню может иметь несколько подменю. Ниже приведена краткая структура:
Table name: site_navigation
id => Primary Key, Auto Increment
parent_id => Index, Defaults Null
menu_name => Varchar
Model => 'Sitemenu_model.php'
use IlluminateDatabaseEloquentModel;
use IlluminateSupportFacadesDB;
class Sitemenu_model extends Model
{
protected $table = 'site_navigation';
public function getParent()
{
return $this->belongsTo('AppModelsbackendSitemenu_model', 'parent_id');
}
public function getChildren()
{
return $this->hasMany('AppModelsbackendSitemenu_model', 'parent_id');
}
}
Controller => 'Pagescontent.php'
use AppModelsbackendSitemenu_model;
class Pagescontent extends Controller
{
$collSiteMenu = Sitemenu_model::with('getChildren')
->orderBy('display_order', 'asc')
->get();
return view('backend.pages.pagescontent.create', ['collSiteMenu'=>$collSiteMenu]);
}
View => 'create.blade.php'
@foreach($collSiteMenu as $menu)
@php
$arrMainMenu[$menu->id] = $menu->menu_name;
@endphp
@endforeach
‘$ arrMainMenu’ содержит только последнюю запись коллекции. Когда я попытался напечатать $menu-> id, он печатается пустым. Даже дочерняя запись не печатает свой идентификатор меню. Даже если я использую приведенный ниже код, вывода все равно нет. Что означает, что атрибут ‘id’ не установлен.
@foreach($collSiteMenu as $menu)
@isset($menu->id)
{{ 'menu id is set to '. $menu->id }}
@endisset
@endforeach
Однако в контроллере, когда я dd ($ collSiteMenu), он печатается ниже:
Collection {#380 ▼
#items: array:12 [▼
0 => Sitemenu_model {#393 ▼
#table: "site_navigation"
#fillable: array:10 [▶]
id: null
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
incrementing: true
#with: []
#withCount: []
#perPage: 15
exists: true
wasRecentlyCreated: false
#attributes: array:13 [▼
"id" => 1
"menu_name" => "About Us"
"parent_id" => null
"url_slug" => "about-us"
"canonical_url" => null
"show_in_nav" => "show_both"
"meta_title" => "About Us"
"meta_keywords" => null
"meta_description" => "this is test description"
"is_active" => "yes"
"display_order" => 1
"created_at" => "2020-09-02 12:39:20"
"updated_at" => "2020-09-04 16:21:51"
]
#original: array:13 [▼
"id" => 1
"menu_name" => "About Us"
"parent_id" => null
"url_slug" => "about-us"
"canonical_url" => null
"show_in_nav" => "show_both"
"meta_title" => "About Us"
"meta_keywords" => null
"meta_description" => "this is test description"
"is_active" => "yes"
"display_order" => 1
"created_at" => "2020-09-02 12:39:20"
"updated_at" => "2020-09-04 16:21:51"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"getChildren" => Collection {#411 ▼
#items: array:2 [▼
0 => Sitemenu_model {#415 ▼
#table: "site_navigation"
#fillable: array:10 [▶]
id: null
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
incrementing: true
#with: []
#withCount: []
#perPage: 15
exists: true
wasRecentlyCreated: false
#attributes: array:13 [▶]
#original: array:13 [▼
"id" => 7
"menu_name" => "Who We Are"
"parent_id" => 1
"url_slug" => "who-we-are"
"canonical_url" => null
"show_in_nav" => null
"meta_title" => "Who We Are"
"meta_keywords" => null
"meta_description" => null
"is_active" => "yes"
"display_order" => 1
"created_at" => "2020-09-02 14:14:03"
"updated_at" => "2020-09-02 14:14:03"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => Sitemenu_model {#416 ▼
#table: "site_navigation"
#fillable: array:10 [▶]
id: null
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
incrementing: true
#with: []
#withCount: []
#perPage: 15
exists: true
wasRecentlyCreated: false
#attributes: array:13 [▶]
#original: array:13 [▼
"id" => 8
"menu_name" => "Our Cause"
"parent_id" => 1
"url_slug" => "our-cause"
"canonical_url" => null
"show_in_nav" => null
"meta_title" => "Our Cause"
"meta_keywords" => null
"meta_description" => null
"is_active" => "yes"
"display_order" => 2
"created_at" => "2020-09-02 14:15:27"
"updated_at" => "2020-09-02 14:15:27"
]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
]
#touches: []
timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
Я искал в Google, но не смог найти решение для этого. Может ли кто-нибудь указать мне, где я ошибаюсь.
С уважением,
Javed
Комментарии:
1. где
getChildren
модель, покажите мне модель getChildren, пожалуйста?2. @EncangCutbray, этот метод определяется в самой модели ‘Sitemenu_model’. Пожалуйста, прокрутите мой вопрос, и вы найдете его.
3. что вы получите, если просто
return $collSiteMenu
4. Это похоже на задание для такого пакета, как
etrepat/baum
который предоставляет вам функциональность вложенного набора. github.com/etrepat/baum Илиlazychaser/laravel-nestedset
. По-видимому, Baum больше не поддерживается. github.com/lazychaser/laravel-nestedset5. Sitemenu_model не является именованием класса PSR-2, что является довольно распространенным стандартом upo, и часть модели является своего рода избыточной. Вместо этого назовите свой класс SiteMenu.