Laravel Relationship with Array value

1.4k views Asked by At

I am using one to one relationship. My model code is:

public function training_type()
{
    return $this->hasone('App\Training_type','id','type');
}

but the parameter "id" is within an array, i tried with following code but not working:

public function training_type()
{
    return $this->hasone('App\Training_type','types.id','type');
}

anyone give me good suggession.

Training_type table structure is,

"company_id": "company1",
"types": [
{
"id": "1",
"name": "Generic"
},
{
"id": "2",
"name": "Compensation and Benefits"
},
{
"id": "3",
"name": "Labor and Employment Law"
}
],
"updated_at": ISODate("2017-08-10T10:24:40.000+05:30")
} 

another table structure is,

{
"company_id": "company1",
"title": "Fire Extinguisher\t",
"content_type": "",
"links": [
{
"link": ""
},
{
"link": ""
}
],
"updated_at": ISODate("2017-08-10T10:24:40.000+05:30"),
"type": "1"
}
2

There are 2 answers

0
Gammer On

The common practice of passing foreign_key to a relationship is :

public function training_type()
{
    return $this->hasone('App\Training_type','foreign_key');
}

The foreign_key is from the table which you want to link.

0
Ahmed Awad On

i was using Laravel with mongodb and jenssegers/laravel-mongodb, i had this documents from models:

User:

{
    "_id" : ObjectId("5bb8013422bb405901652cd9"),
    "name" : "ahmed",
    "email" : "[email protected]",
    "role" : {
        "name" : "admin",
        "_id" : ObjectId("5bb8013422bb405901652cd2")
    }
}

Role:

{
    "_id" : ObjectId("5bb8013422bb405901652cd2"),
    "name" : "admin"
}

and i wanted to use the hasOne relation to get the use role, i did this in the User model:

public function role()
    {
        return $this->hasOne('App\Models\Role', '_id', 'role._id');
    }

as you can see, i inserted the role as an array with: id, name in the User documents in DB, when i tested this with:

dd(\Auth::user()->role);

it worked just as fine.