【发布时间】:2014-09-01 21:41:29
【问题描述】:
我遇到了 Eloquent morphOne 关系的问题,它正在创建新条目而不是更新已经存在的条目。
基本上我有许多模型(例如,假设Person 和Building)都需要一个位置,所以我创建了一个Location 模型:
class Location extends Eloquent {
public function locationable()
{
return $this->morphTo();
}
}
然后在我的其他模型中,我有这个:
class Person extends Eloquent {
// ...
/**
* Get the person's location
*
* @return Location
*/
public function location()
{
return $this->morphOne('Location', 'locationable');
}
// ...
class Building extends Eloquent {
// ...
/**
* Get the building's location
*
* @return Location
*/
public function location()
{
return $this->morphOne('Location', 'locationable');
}
// ...
当我运行以下测试代码时,它会很好地创建位置条目,但如果我重复它,它会创建更多条目。
$person = Person::first();
$loc = new Location;
$loc->lat = "123";
$loc->lng = "321";
$person->location()->save($loc);
我在这里做错了吗?我本来希望morphOne 将其限制为每种类型一个条目,因此下表中的最后一个条目不应该存在:
+---------------------+--------------------------+
| locationable_id | locationable_type |
+---------------------+--------------------------+
| 2 | Building |
| 3 | Building |
| 2 | Person |
| 2 | Building |
+---------------------+--------------------------+
【问题讨论】:
-
不,你没有做错。这就是它的工作原理。多态关系适用于简单的事情,但越深入,发现的错误就越多。
-
那么您是否建议尽可能避免使用它们?除了创建多态关系之外,我做任何其他事情都没有意义。 1) 有人建议做一个简单的 if else 检查
orderable_type是否为空然后创建,否则更新,您对此有何看法? 2) i.imgur.com/gPmh1OK.png 对此有何看法?很想听听。谢谢你。
标签: laravel laravel-4 eloquent polymorphism