duanbichou4942 2016-08-21 01:43
浏览 44
已采纳

Laravel与条件有很多很多关系

I have 4 tables users, opportunities, level_translations and levels

users
id, name, email

opportunities
id, client_name, user_id, total_price

levels
id, min, max

level_translations
id, name, description, locale, level_id

I want to get level name in current locale for given user id .. i'm using laravel-translatable package to localize my application

to get level it should be something like this

select * from levels where sum(opportunities.total_price) < levels.max and sum(opportunities.total_price) > levels.min 
  • 写回答

1条回答 默认 最新

  • douliaodun9153 2016-08-24 00:47
    关注

    I found a solution. my solution contain tow parts
    first part
    creating a MYSQL Function, i call it sumUserOwnopportunities(USERID)

        DELIMITER $$
    CREATE  FUNCTION `sumUserWonOpportunities`(USERID INT) 
     RETURNS double
    BEGIN
         DECLARE TOTAL_SUM DOUBLE DEFAULT 0;
         SELECT SUM(opportunities.total_price) from opportunities 
         WHERE opportunities.user_id=USERID AND (opportunities.status=1 OR opportunities.status=2) INTO TOTAL_SUM;
            RETURN TOTAL_SUM;
    END$$
    DELIMITER ;
    

    second part
    in User model

    function level(){
       return  Level::where(function ($q){
                $q->where("min","<",DB::raw(" sumUserWonOpportunities($this->id)"))
                ->where("max",">",DB::raw(" sumUserWonOpportunities($this->id)"));
            })->first();
    }
    

    now I can call

    $user=User::find(1);
    $level=$user->level()->name;// it will return level name in current locale 
    

    I hope this useful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页