Reputation: 5283
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.
<?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');
}
}
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.
Upvotes: 0
Views: 250
Reputation: 62368
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"
Upvotes: 1