Thursday, January 31, 2019

Laravel hasMany and belongsTo parameters

No comments
Hi Dear Friends,

In this post We would like to share infinity knowladge My Good experience and Best solution For .

Laravel Examples

To simplify the syntax, think of the return $this->hasMany('App\Comment', 'foreign_key', 'local_key'); parameters as:
  1. The model you want to link to
  2. 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)
  3. 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()).
Try this it will help you and for more information click here: Laravel Examples.

Read :

I hope you like this Post, Please feel free to comment below, your Any Idea, suggestion and problems if you face - I am here to Resolve your Any problems.
We hope it can help you...

No comments :

Post a Comment