duanruoyu6675 2016-07-28 18:22
浏览 69
已采纳

自定义查询功能laravel

I often need to perform this query:

$Op = JobCardOp::where([
        ['JobCardNum', '=', $JobCardNum ],
        ['OpNum', '=', $OpNum ]
        ])->first();

So rather than writing this out every time I want a function like:

 public function getOp($JobCardNum, $OpNum)
{
    $Op = JobCardOp::where([
        ['JobCardNum', '=', $JobCardNum ],
        ['OpNum', '=', $OpNum ]
        ])->first();
    return $Op;
}

That I can call in my controller. Where should I define my function, at the moment the I only need it in one controller but I may need it an another if thats possible. Any help appreciated.

  • 写回答

2条回答 默认 最新

  • douguyi3903 2016-07-28 18:32
    关注

    You could put this method on your Model if you wanted to as a static function.

    public static function getOp($cardNum, $opNum)
    {
        return static::where([
            ['JobCardNum', '=', $cardNum],
            ['OpNum', '=', $opNum]
        ])->first();
    }
    
    // controller
    
    $res = YourModel::getOp($cardNum, $opNum);
    

    Or add a query scope to the model

    public function scopeGetOp($query, $cardNum, $opNum)
    {
        return $query->where([
            ['JobCardNum', '=', $cardNum],
            ['OpNum', '=', $opNum]
        ]);
    }
    
    // controller
    
    $res = YourModel::with(...)->getOp($cardNum, $opNum)->first();
    

    Kinda depends how you want to use it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退