Eloquent: use a different column as the primary key in relation

I have a Books table: with identifier (int) and ISBN (string) ISBN is a unique key. I have another table where I store isbn for a book. On the model of the book I have: $ this-> hasMany ('Other', 'isbn', 'isbn');

But it ignores isbn. Do you know any way to do this?

Temporary fix:

$this->primaryKey = 'isbn'; return $this->hasMany('Other', 'isbn'); 
+6
source share
4 answers

This is not possible - there are only a few examples when you want to associate a unique column in a table that is also not pk. However, other structures have developed methods for changing the primary key, and no one has formally requested it for Laravel. You can write an offer on GitHub , and it may be included in a future version.


Looking at your specific example for a moment - this may have unexpected results when you come to use relationships in impatient loading situations, and this takes into account only one side of the relationship. When you add applyTo to Other, you will have the opposite problem.

It is possible to establish communication through isbn; however, this will take the form of a hasOne book ISBN, ISBN belongs to the book, ISBN hasMany Others, Other belongs to ISBN; and access to the properties will look like $book->isbn->others or $other->isbn->book .

My last suggestion was to expand the book and set the primary key of the new class as isbn and base all your relationships on this model. This is not ideal, but it would be less painful that some other solutions.

+1
source

Recently I stumbled upon the same problem, I'm still not sure if this will work, but as an idea:

 class Book { public function isbn() { // instead of hasMany return ISBN::where('isbn', $this->isbn); } } 
+1
source

If I read this right, you can achieve this by overriding getKeyName.

  public function getKeyName(){ return $yourKeyName; } 
+1
source

Since at least 4.2, you can specify a local key in hasMany .

From the documentation ( 4.2 , 5.2 ):

 return $this->hasMany('Comment', 'foreign_key', 'local_key'); 
0
source

Source: https://habr.com/ru/post/945006/


All Articles