简体   繁体   中英

Polymorphic relations

I have a Link model, which needs a field that refers to either the Page , Redirect or Gallery model. I would like to be able to do something line $link->obj and have that return either the Page, Redirect or Gallery object depending on which one was saved to it.

Polymorphic relations appear to be what I'm looking for, except that I can't seem to get this approach to work.

Current code

<?php

$item = Page::find (1);

$link = new Link ();
$link->linkable ()->save ($item);
$link->save ();

Models

<?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');
    }
}

The link database table has linkable_id and linkable_type fields.

I suppose I must be misunderstanding the documentation, because this does not appear to work.

You're close. Assuming you have your database setup correctly, the only issue I see is you calling save() on the morphTo relationship.

The morphTo side of the relationship is the belongsTo side. The belongsTo side does not use the save() method, it uses the associate() method.

So, the code you're looking for should be something like:

$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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM