Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent morphOne relationship doesn't limit to one relation

I am having a issue with an Eloquent morphOne relationship where it is creating new entries rather than updating the one that already exists.

Basically I have a number of models (for example, let's say Person and Building) that both need a location, so I have created a Location model:

class Location extends Eloquent {

    public function locationable()
    {
        return $this->morphTo();
    }

}

Then in my other models I have this:

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

    // ...

When I run the following test code, it creates the location entry fine, but if I repeat it, it creates more entries.

$person = Person::first();

$loc = new Location;

$loc->lat = "123";
$loc->lng = "321";

$person->location()->save($loc);

Am I doing something wrong here? I would have expected morphOne to constrain this to one entry per type, so the last entry in the table below should not exist:

+---------------------+--------------------------+
|  locationable_id    |   locationable_type      |
+---------------------+--------------------------+
|  2                  |  Building                |
|  3                  |  Building                |
|  2                  |  Person                  |
|  2                  |  Building                |
+---------------------+--------------------------+
like image 793
Keith Avatar asked Jul 11 '14 09:07

Keith


1 Answers

Maybe I'm late for the party, but this worked for me!

# Do we have location already?
if($person->location) {
    return $person->location()->update($location);
}
return $person->location()->create($location);
like image 96
Murwa Avatar answered Nov 07 '22 12:11

Murwa