2016-11-10 10:01



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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • douchuang8359 douchuang8359 5年前

    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 drn34916 5年前

    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.

    点赞 评论 复制链接分享