2016-11-10 10:01
浏览 20


I have two types of user: client, manager. are stored in separated tables.

Each of then have unique nickname.

So, I need to open profile by nickname.

For Client is:

$client = Client::where("nickname", $nickname)

For Manager is:

$manager = Manager::where("nickname", $nickname)

So, I try to make universal function that dewtect where is client and manager and execute the appropriate query.

How can I improve this code and detect type of user only by nickename?

图片转代码服务由CSDN问答提供 功能建议

我有两种类型的用户: client manager 。 存储在单独的表中。


所以,我需要通过 nickname


  $ client = Client :: where(“nickname”,$ nickname)

For Manager是:

  $ manager = Manager :: where(“nickname”,$ nickname)


我如何改进这一点 代码并仅通过nickename检测用户类型?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douchuang8359 2016-11-10 10:06

    You should use one model for this, I guess it would be best way to handle clients and managers.

    If for some reason you want to use two models, you can create method and put it in Client model since most of queries will be for clients:

    public function getClientOrManagerByNickname($nickname) {
        $client = $this->where('nickname', $nickname)->first();
        return is_null($client) ? (new Manager)->where('nickname', $nickname)->first() : $client;

    This code will create one query if client is found and will return this client. Or it will create two queires and will return manager. If there is no client and manager with this nickname, it will return null.

    打赏 评论
  • drn34916 2016-11-10 10:44

    As I said I would suggest something a bit more complex but that to me would be less prone to make mistakes because of a confusion on the Model returned.

    I would suggest something along this:

    $modelname = getModelName(); $values = $modelName::where(1);

    Where the function getModelName() would just return the ModelName. I'm aware that this implies going through the DB another time and it increases the cost of the operation but I would rather loss a bit of performance and have more coherence in the code.

    That's my personal opinion though.

    打赏 评论

相关推荐 更多相似问题