Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

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";

Upvotes: 1

Views: 1508

Answers (2)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

I think your code need to update like:

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

Hope this work for you!

Upvotes: 0

Rajender Joshi
Rajender Joshi

Reputation: 4205

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;
}

Upvotes: 1

Related Questions