我正在嘗試創建我的第一個多態關係,並且遵循了網站上的文檔並在網上查了幾個教程,所有教程都遵循類似的主題。我有3個表格,頁面,菜單和菜單項。菜單項將始終是菜單的子項,並且可能是頁面(如果是鏈接)或另一個菜單(如果是子菜單)。我的表是:Laravel多態關係查詢尋找錯誤的列
頁面
+----+------+----------+------+--------+-----------+-----------------+------------+------------+------------+
| id | name | url_slug | file | layout | seo_title | seo_description | created_at | updated_at | deleted_at |
+----+------+----------+------+--------+-----------+-----------------+------------+------------+------------+
菜單
+----+------+------------+------------+
| id | name | created_at | updated_at |
+----+------+------------+------------+
菜單項
+----+---------+-------------+---------------+-------+------+-------+------------+------------+
| id | menu_id | itemable_id | itemable_type | label | left | right | created_at | updated_at |
+----+---------+-------------+---------------+-------+------+-------+------------+------------+
所以對於菜單ITE ms表menu_id
是菜單項的父項,它與菜單表具有一對多的關係。 itemable_id
和itemable_type
在polymophic關係中使用,itemable_id
應引用菜單或頁面中的id
列,具體取決於itemable_type
是什麼,這將是Menu或Page模型。
要建立這種關係,我添加的方法我的模型是這樣的:
頁
/**
* Fetch the menu items this page is linked to.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function menuItems()
{
return $this->morphMany('App\Modules\Menu\Models\MenuItem', 'itemable');
}
菜單
/**
* Fetch all child menu items belonging to this menu.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function childItems()
{
return $this->hasMany('App\Modules\Menu\Models\MenuItem');
}
/**
* Fetch all menu items linked to this menu.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function menuItems()
{
return $this->morphMany('App\Modules\Menu\Models\MenuItem', 'itemable');
}
菜單項
/**
* Fetch the menu this item belongs to.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function menu()
{
return $this->belongsTo('App\Modules\Menu\Models\Menu');
}
/**
* Fetch the models this menu item links to.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function itemable()
{
return $this->morphTo();
}
我已經創建了所有的表格,現在我正試圖播種它們。我的種子是這樣的:
public function run()
{
$menu = Menu::create([
'name' => 'Main'
]);
foreach ([
[
'page_id' => 1,
'label' => 'Home',
'left' => 1,
'right' => 2
],
[
'page_id' => 2,
'label' => 'About Us',
'left' => 3,
'right' => 4
]
] as $arr)
{
/* @var $page Page */
$page = Page::findOrFail($arr['page_id']);
$item = new MenuItem($arr);
$page->menuItems()->save($item);
$item->menu()->associate($menu);
}
}
但我不斷收到錯誤,當我運行它有關page_id
列不存在。確切的錯誤是
[Illuminate\Database\QueryException]
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'page_id' in 'field list' (SQL: insert into `menu_items` (`page_id`, `label`, `left`, `right`, `itemable_type`, `itemable_id`, `updated_at`, `created_at`) values (1, Home, 1, 2, App\Models\Page, 1, 2016-08-03 12:32:21, 2016-08-03 12:32:21))
一切有關查詢是很好,除了它試圖填充page_id
還有itemable列。它爲什麼這樣做?我怎樣才能解決它?
Doh>。<,因爲我有一個可填充的數組,我不認爲它會從數組中取page_id。它甚至不會發生在我身上。謝謝。 – Styphon