I just tried the example for the Polymorphic Relation from the docs:
class Photo extends Eloquent {
public function imageable()
{
return $this->morphTo();
}
}
class Staff extends Eloquent {
public function photos()
{
return $this->morphMany('Photo', 'imageable');
}
}
class Order extends Eloquent {
public function photos()
{
return $this->morphMany('Photo', 'imageable');
}
}
With this code I tried to add a new Photo to a loaded Order:
// load order
$order = Order::find(1);
// create photo
$photo = new Photo
$photo->path = 'foo';
// save photo to the loaded model
$order->photos()->save($photo);
I noticed that imageable_type
is not set automatically. Is this not supported and do I have to set it manually or am I doing something wrong here?
I'll look into it. For now, this should work:
$photo = $order->photos()->create(array('path' => 'foo'));
Added save
method. Give it a go now.
Thank you Taylor ... works now.
I'm experiencing the same issue with the following code.
class History extends Eloquent {
protected $table = 'history';
protected $fillable = array(
'historable_id',
'historable_type',
'eventable_id',
'eventable_type'
);
public function historable()
{
return $this->morphTo();
}
public function eventable()
{
return $this->morphTo();
}
}
class User extends Eloquent {
...
public function history()
{
return $this->morphMany('History', 'historable');
}
}
$history = $user->history()->create(array(
'eventable_id' => $event->id,
'eventable_type' => 'FooEvent'
));
The historable_id
and historable_type
are not populated.
--------------------------------------------------------------------------------------------------
| id | historable_id | historable_type | eventable_id | eventable_type | created_at | updated_at |
--------------------------------------------------------------------------------------------------
| 1 | | | 1 | FooEvent | -------- | -------- |
--------------------------------------------------------------------------------------------------
Here's a dump of the $history
object and a dump of the query log.
I've been trying something similar to eoconnell. By that I mean trying to store more than 1 polymorphic relations in a single row. While I can manually set the 2nd I'd love a way to set both with 1 create()..
Most helpful comment
Added
save
method. Give it a go now.