Reputation: 504
I have a table store, and store has many libraries, in library I have foreign key of store store_id
.
Store table
id(PK)
Library table
id(PK)
store_id(FK)
I'm confused with hasMany
and belongsTo
parameters include, in the docs it says
return $this->hasMany('App\Comment', 'foreign_key');
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
Which table of hasMany foreign_key and local_key came from? Same with belongsTo which table of foreign_key and other_key came from?
Store model
public function library(){
return $this->hasMany('App\Library', 'what_foreign_key_should_be_here','what_other_key_should_be_here');
}
Library model
public function stores(){
return $this->belongsTo('App\Stores', 'what_foreign_key_should_be_here', 'what_other_key_should_be_here');
}
Because sometimes I change my primary key id of a table to other name like sid, so I always want to specify which is foreign key and primary key
Upvotes: 31
Views: 97834
Reputation: 415
Store table:
store_id (PK)
Library table:
library_id (PK) library_fk_store_id (FK)
Store model:
public function libraries()
{
return $this->hasMany(Library::class, 'library_fk_store_id','library_id');
}
Library model:
public function store()
{
return $this->belongsTo(Store::class, 'library_fk_store_id', 'store_id');
}
`library_fk_store_id`
`Store model -> library_id` `Library model -> store_id`
`libraries() -> library_id` `store() -> store_id`
Upvotes: 2
Reputation: 2993
Try this one. It works. Add this to your model.
Library model
public function store()
{
return $this->belongsTo(Store::class, 'store_id', 'id');
}
Store model
public function libraries()
{
return $this->hasMany(Library::class);
}
example code.
$store = Store::find(1);
dd($store->libraries);
Because in this case a store has many libraries, the Store
model has a libraries()
function. Refer to last line of James' answer for more information on this standard.
Upvotes: 15
Reputation: 16339
To simplify the syntax, think of the return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
parameters as:
id
column of the current table (unless you are specifying the third parameter, in which case it will use that)id
column of the current tableIn your circumstance, because you have used store_id
in the libraries
table, you've made life easy for yourself. The below should work perfectly when defined in your Store
model:
public function libraries()
{
return $this->hasMany('App\Library');
}
Behind the scenes, Laravel will automatically link the id
column of the Store
table to the store_id
column of the Library
table.
If you wanted to explicitly define it, then you would do it like this:
public function libraries(){
return $this->hasMany('App\Library', 'store_id','id');
}
$store->libraries() or $library->store()
).Upvotes: 54