jeudi 23 avril 2020

Multiple foreign keys referencing to one primary key

I've been struggling with this for a couple of weeks and I can't seem to find the answer anywhere.

I am trying to reference three foreign keys into one primary key on another table.

Here are some information:

User Table

|---------------------|
|        id           |
|---------------------|
|         1           |
|---------------------|
|         2           |
|---------------------|
|         3           |
|---------------------|

Service Table

Service table with three foreign keys referencing to user_id

|---------------------|------------------|------------------|------------------|
|        id           |     tenant       |  service_person  |     landlord     |
|---------------------|------------------|------------------|------------------|
|         1           |        1         |         2        |         3        |
|---------------------|------------------|------------------|------------------|

User Model

    public function service(){
        return $this->hasMany(Service::class, 'id');
    }

Service Model

    public function tenant(){
        return $this->belongsTo(User::class, 'id', 'tenant');
    }

    public function service_person(){
        return $this->belongsTo(User::class, 'id', 'service_person');
    }

    public function landlord(){
        return $this->belongsTo(User::class, 'id', 'landlord');
    }

So when I try to query with User::find()->service with tinker, only one of my three users find results, which is the service_person. The other ones just return an empty object.

Query result:

>>> User::find(1)->service
=> Illuminate\Database\Eloquent\Collection {#3125
     all: [
       App\Service {#3156
         id: 1,
         tenant: 2,
         service_person: 1,
         landlord: 3
       },
     ],
   }
>>> User::find(2)->service
=> Illuminate\Database\Eloquent\Collection {#3165
     all: [],
   }
>>> User::find(3)->service
=> Illuminate\Database\Eloquent\Collection {#3166
     all: [],
   }

Any idea on how can I achieve that?

Ideally I do not want to do a many to many relationship and create a pivot table.

Thank you in advance



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire