Skip to content

Unexpected QueryBuilder hasOne() Behavior #212

@j42

Description

@j42

https://stackoverflow.com/questions/23621572/laravel-mongodb-eloquent-hasone-relationship-broken-jensseggers

Laravel: 4.1

The (most supported) mongo package for Laravel doesn't seem to be working with hasOne relationships (or else I am misunderstanding them).

In this example, embedsOne works properly;

{
    "_id" : ObjectId("537174b4d265984c2a8b4568"),
    "location" : {
        "_id" : ObjectId("53715255d2659895298b456b"),
        "city" : "New York",
        "state" : "NY",
    }
}

whereas it is defined like so:

public function location() {
    return $this->embedsOne('Location', 'location');
}

The Problem

The hasOne relationship doesn't seem to be creating the related key in the document, when it is defined like so:

public function customer() {
    return $this->hasOne('Customer'); // I also tried [, 'customer_id', 'customer_id'] to explicitly define foreign/local keys
}

Additionally, making any adjustments to the $fillable attribute doesn't seem to change what's saved to the model.

The actual process of saving to the model is like so:

// Associate with Customer
$Job->customer()->save($Customer);

Which returns a success response, however when I look up the document in the mongo CLI, I don't see a customer_id field anywhere linking the relation. Additionally $Job->customer returns null and $Job->customer() returns a collection containing all documents.

Lastly, worth noting, inverse relationships belongsTo are defined (properly) on both the Customer and Service models which are being attached.

Does anyone have any idea why this isn't working as expected, and a reference isn't being saved to the document?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions