JGL JGL - 1 month ago 23
PHP Question

Laravel 5.3 belongsToMany won't work

I have to work with tables I didn't create so they don't follow Laravel's rules (no icremented primary key, no logical foreign and local keys, etc.). Here are my tables : users, users_jobs and jobs.

My pivot table, users_jobs, has a composite key (job_reference and job_node). I know Laravel don't handle composite key so I added a new field job_key, which is just my two keys concatenated, in users_jobs and jobs.

In my User model I have this :

public function jobs() {
return $this->belongsToMany('\App\Job', 'users_jobs', 'username', 'job_key');
}


It returns no result...

But when I try using one of my composite key it does have result. Wrong ones because it's only one of the two keys but still it works !

public function jobs() {
return $this->belongsToMany('\App\Job', 'users_jobs', 'username', 'job_reference');
}


Any clue why my new key doesn't work ?




Edit :

When I output the queries I have this :


select
jobs
.*,
users_jobs
.
username
as
pivot_username
,
users_jobs
.
job_key
as
pivot_job_key
from
jobs
inner join
users_jobs
on
jobs
.
id
=
users_jobs
.
job_key
where
users_jobs
.
username
in (?)


Of course it doesn't find anything, it's using id as foreign key rather than _job_key_ !

And I can't make it work anymore with job_reference. I know I have something wrong in my code but I can't see what and it's driving me crazy...

Answer
class User extends Model{
    protected $primaryKey = 'username';
    public function jobs() {
        return $this->belongsToMany('App\Job', 'users_jobs', 'username', 'username');
    }
}

class Jobs extends Model{
    protected $primaryKey = 'job_key';
    public function users() {
        return $this->belongsToMany('App\User', 'users_jobs', 'job_key', 'job_key');
    }
}