我对 Eloquent 有疑问morphOne
它创建新条目而不是更新已存在的条目的关系。
基本上我有很多模型(例如,假设Person
and Building
)两者都需要一个位置,所以我创建了一个Location
model:
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 |
+---------------------+--------------------------+