I have these db tables:
author (atr_id pk) // model : Author
category (ctg_id pk) // model : Category
post (pst_id pk, pst_atr_id fk) // model : Post
post_categories (pct_pst_id fk, pct_ctg_id fk) // pivot : PostCategories
how to define the hasMany, belongsTo, belongsToMany parameters with custom names?
Model : Author
public function getPosts()
{
return $this->hasMany('App\Post', ?, ?);
}
Model : Post
public function getAuthor()
{
return $this->belongsTo('App\Author', ?, ?);
}
public function getCategories()
{
return $this->belongsToMany('App\Category', ?, ?, ?);
}
Model : Category
public function getPosts()
{
return $this->belongsToMany('App\Post', ?, ?, ?);
}
Model : Author
<?php
public function getPosts(){
return $this->hasMany('App\Post','pst_atr_id');// author table's foreign key in Post table.
}
Model : Post
<?php
public function getAuthor(){
return $this->belongsTo('App\Author','pst_atr_id','atr_id'); // first is foreign key of author table in this current table and second is primary key name of author table.
}
public function getCategories(){
return $this->belongsToMany('App\Category','post_categories','pct_pst_id ','pct_ctg_id'); /* 'post_categories' is the pivot table. Rest 2 parameters- first is foreign key present in post_categories of the current model, second is foreign key present in post_categories of the model we are relating with*/
}
Model : Category
<?php
public function getPosts(){
return $this->belongsToMany('App\Post','post_categories ','pct_ctg_id','pct_pst_id');
/* 'post_categories' is the pivot table. Rest 2 parameters- first is foreign key present in post_categories of the current model, second is foreign key present in post_categories
of the model we are relating with*/
}
Author : $this->hasMany('App\Post', 'pst_atr_id', 'atr_id');
Post : $this->belongsTo('App\Author', 'pst_atr_id', 'atr_id');
Post : $this->belongsToMany('App\Category', 'post_categories', 'pct_pst_id', 'pct_ctg_id');
Category : $this->belongsToMany('App\Post', 'post_categories', 'pct_ctg_id' 'pct_pst_id');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With