[英]Polymorphic relations
我有一個Link
模型,它需要一個引用Page
, Redirect
或Gallery
模型的字段。 我希望能夠執行$link->obj
並根據保存到其中的那個返回Page,Redirect或Gallery對象。
多態關系似乎是我要尋找的,除了我似乎無法使這種方法起作用。
<?php
$item = Page::find (1);
$link = new Link ();
$link->linkable ()->save ($item);
$link->save ();
<?php
class Link extends Eloquent
{
protected $table = 'link';
public function linkable ()
{
return $this->morphTo ();
}
}
class Page extends Eloquent
{
protected $table = 'page';
public function linkable ()
{
return $this->morphOne ('Link', 'linkable');
}
}
class Redirect extends Eloquent
{
protected $table = 'redirect';
public function linkable ()
{
return $this->morphOne ('Link', 'linkable');
}
}
class Gallery extends Eloquent
{
protected $table = 'gallery';
public function linkable ()
{
return $this->morphOne ('Link', 'linkable');
}
}
link
數據庫表具有linkable_id
和linkable_type
字段。
我想我一定對文檔有誤解,因為這似乎行不通。
你近了 假設您的數據庫設置正確,我看到的唯一問題是您在morphTo
關系上調用save()
。
的morphTo
的關系的側是belongsTo
側。 belongsTo
方不使用save()
方法,而是使用associate()
方法。
因此,您要查找的代碼應類似於:
$item = Page::find(1);
$link = new Link();
$link->linkable()->associate($item); // associate the belongsTo side
$link->save();
// and to show it worked:
$link->load('linkable');
$page = $link->linkable;
echo get_class($page); // prints "Page"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.