mardi 5 juillet 2016

Laravel 5.2: how to specify two relationships on the same model based on the value of a field?

I've two models, Post and Term. Basically Term represents a category or a tag (type field in the db table for terms). A post belongs to a single category, but it can have many tags. A category/tag can have many posts.

The Term model will have a function like:

 public function posts(){
    return $this -> hasMany('App\Post');
}

but I don't understand if I should have two functions in the Post model: one for categories and one for tags also if the same database table contains both. Something like:

 public function tags(){
    return $this -> hasMany('App\Term'); // specifying the type in some way
}

public function category(){
    return $this -> hasOne('App\Term'); // specifying the type in some way
}

How to take into account the value of the field type of terms table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire