Search code examples
phplaravellaravel-5.3

Laravel relation foreign key pointing to UNIQUE constraint


users table:

id    int primary key, auto increment
r_id  varchar unique
name  varchar

books table:

id       int primary key, auto increment
user_id  foreign key to r_id in users table
name     varchar

The relation in User Model:

return $this->hasMany('App\Book', 'user_id');

By default, user_id FOREIGN KEY is pointing to a PRIMARY KEY id. How can i make it pointing to a UNIQUE r_id?

If Only, r_id is primary key, we can pass it with third argument and overriding $primaryKey property:

return $this->hasMany('App\Book', 'user_id','r_id');
protected $primaryKey = "r_id";

Solution

  • By default Eloquent orm expect local key to be id. To override it you can pass in third argument in relationship.

    https://laravel.com/docs/5.2/eloquent-relationships#one-to-many

    $this->hasMany('App\Model', 'foreign_key', 'local_key')
    

    So, your relation can be

    return $this->hasMany('App\Book', 'user_id', 'r_id');
    

    Update:

    I recall, I ran into similar situation recently. Can you try this and revert me back. I will update the answer with details later. Add following method in your User model and test. Thanks

    public function getRIdAttribute($value)
    {
        return $value;
    }