[英]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.