簡體   English   中英

多態關系

[英]Polymorphic relations

我有一個Link模型,它需要一個引用PageRedirectGallery模型的字段。 我希望能夠執行$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_idlinkable_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM