Laravel hasMany and belongsTo parameters
To simplify the syntax, think of the return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
parameters as:
- The model you want to link to
- The column of the foreign table (the table you are linking to) that links back to the
id
column of the current table (unless you are specifying the third parameter, in which case it will use that) - The column of the current table that should be used - i.e if you don't want the foreign key of the other table to link to the
id
column of the current table
In 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');
}
- A model standard is that singularly-named functions return a belongsTo, while a plural function returns a hasMany (ie.
$store->libraries() or $library->store()
).
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');
}
- Foreign keys are identical in both methods:
`library_fk_store_id`
- Local/Owner keys are the ids from the opposite model/table:
`Store model -> library_id` `Library model -> store_id`
- Local/Owner keys has the same name from the method names:
`libraries() -> library_id` `store() -> store_id`
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.