Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasMany, belongsTo, belongsToMany parameters with custom names?

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', ?, ?, ?);
}
like image 223
eng Avatar asked Jan 20 '26 22:01

eng


2 Answers

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*/
 }
like image 63
nice_dev Avatar answered Jan 22 '26 13:01

nice_dev


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');
like image 41
eng Avatar answered Jan 22 '26 11:01

eng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!