Ad

Relationship Between User And Category OctoberCMS

how to establish a relationship between the user and the category?

A category has more than one user, and a user belongs to a category

I add category_id in the user table

on the frontend I display the list of users with the plugin builderbut I also want to display the category of the user

I use the RainLab user plugin

Help me please,

thank you in advance

Ad

Answer

it seems you need to extend user model and add category relation runtime

You need to add this code to your plugin's boot method

public function boot()
{
    //Extending User Plugin
    \RainLab\User\Models\User::extend(function($model) {

        $model->hasOne['category'] = 'HardikSatasiya\Plugin\Models\Category';

    });
}

this code will add dynamic relation to user model so now you can use this relation directly like $userModel->category->name

so now in list you can use below code

{% for user in records %}
    Email : {{ user.email }}
    Category : {{ user.category.name }}
{% endfor %}

if any doubt please comment.

Ad
source: stackoverflow.com
Ad