与用户建立模型关系,用户只能访问自己的数据

making model relationship to user, user can only access its own data

我有 2 个主模型和一些带有主模型关系控制器的子模型,现在我需要将用户 ID 添加到主模型和子模型中,这样用户只能访问自己的数据,因为用户数据保持不变 table。 我创建了 belongsToManyuser.php 到模型的关系,反之亦然 pivot table 但没有任何反应 我不知道该怎么做,因为我需要简化数据库管理以防我需要进行迁移.. 有人可以分享你的经验吗..

我可以建议您只需将 user_id [for Backend => backend_users_id ] 添加到模型中,您只想让所有者访问哪些数据。

现在在 main model 中您可以定义 belongsTo 关系,在用户中您可以定义 hasMany 关系

main model relationship [if you want to restrict the user in backend side then you need to add backend user relation and same in backend user model]

class MainModel extends Model
{
    // Adding relation to user model
    public $belongsTo = [
        'user' => 'RainLab\User\Models\User',
        'backend_users' =>'Backend\Models\User' // for Backend
    ];

}

adding a relation to the user model [ you need to put this code in your plugin's boot method ]

// Extending User Model
\RainLab\User\Models\User::extend(function($model) {
    $model->hasMany['mainmodel'] = ['HardikSatasiya\Plugin\Models\MainModel'];
});

// for Backend users
\Backend\Models\User::extend(function($model) {
    $model->hasMany['mainmodel'] = ['HardikSatasiya\Plugin\Models\MainModel'];
});

Now access data [ Front-end side ]

// Returns the signed in user
$user = \Auth::getUser();
dd($user->mainmodel); // it will return collection of related mainmodels

// it will return related data and now its filter by owner
dd($user->mainmodel[0]->otherRelatin); 


// for Backend users
// Returns the signed in user
$user = \BackendAuth::getUser();
dd($user->mainmodel); // it will return collection of related mainmodels

// it will return related data and now its filter by owner
dd($user->mainmodel[0]->otherRelatin); 

Example filter data in listview based on logged in admin user [ OctoberCMS do not give such functionality out of the box, you can not hide a portion of data records you can hide entire menu or all records based on rights and roles but can not hide partial records ]

public function listExtendQuery($query)
{
    $user = \BackendAuth::getUser();
    $query->where('backend_users_id', $user->id);
}

to add backend_users_id you can use this code

class MainModel extends Model {

    public function beforeSave()
    {
        $user = \BackendAuth::getUser();
        $this->backend_users_id = $user->id;
    }
}

如有疑问请评论。