问题
I'm trying to implement a multi-tenant application. I have different customers that are using the same code. But each customer gets its own entry script with its own configuration. The customer id is accessible by Yii::$app->params['customerId']
. Note: I have to distinguish the customers that way because there is no login/authentication. Anyway, assume the controller action is called and a customer id is given with the parameter.
Now I have some tables and each has a column for the customer id. I have created model classes with gii and all is fine. But now I've got the problem that I have to check or tell for each database operation which customer id has to be used. So on every db operation (Query) I can add an ->andWhere(['customerId' => Yii::$app->params['customerId']])
. This is tedious and error prone, of course.
Is there a way to simplify this? Consider that there are find, insert, update, delete and join operations. I can probably use Customized query classes but I don't know what I have to do there and I'm not sure if it helps with inserts/updates/deletes. Consider also that there are related tables with the same customer id colum. hasMany()
and hasOne()
should also reflect this.
My aim is to have the customer id be as transparent as possible. I don't want to think about it. So I could imagine some kind of abstract query class that uses a certain column (the customer id column) for all operations and that gets the customer id somehow (injected or with Yii::$app->params['customerId']
).
My assumption is that I need to do this mainly in the model. I think controllers are less concerned by this topic.
Any suggestions how to do that?
回答1:
In situations like the ones you described a form solution it is to manage data with database views able to filter the data for customer id. This involves dynamic access to the tables / views that you can manage through changing function tableName () of the model. Creating views can also be automated with functions DML database. This is only a brief introduction i hope this is useful for you.
来源:https://stackoverflow.com/questions/31434768/yii2-how-to-let-activerecord-models-only-see-certain-database-data