hasOne() method. addresses table requires user_id. users table does not require address_id if User model uses hasOne().hasOne() in Address model, users table must have address_id field.hasMany() inside User model, articles table must have user_id. But users table does not require article_id. Also, Article model does not require belongsTo() method. SourcebelongsTo() inside Article model, articles table must have user_id. But users table does not require article_id. Also, User model does not require hasMany() method. Sourceusers table should contain country _id column and articles table should contain user_id column. Now the Country model must have the following method:public function articles() {
return $this->hasManyThrough('Article', 'User', 'country_id', 'user_id') ;
}
users table and fourth parameter is the foreign key inside comments table.role_user need to be created with columns user_id and role_id. users table or roles table does not require role_id or user_id respectively. Either or both of the model can use belongsToMany() method.users table and articles table does not need comment_id. The comments table must have commentable_id and commentable_type. The Comment model must havepublic function commentable() {
return $this->morphTo();
}
comments table.User and Article model must havepublic function comments() {
return $this->morphMany('Comment', 'commentable');
}
Comment model.commentable_type.boot() function of AppServiceProvider add the follwing codepublic function boot()
{
Relation::morphMap([
'User' => 'App\User',
'Article' => 'App\Article',
// etc
]);
}
use Illuminate\Database\Eloquent\Relations\Relation;
Labels: Laravel, Theme development