代码之家  ›  专栏  ›  技术社区  ›  Sandeep Sudhakaran

如何在Laravel中调用模型函数后调用雄辩函数

  •  2
  • Sandeep Sudhakaran  · 技术社区  · 7 年前

    //控制器.php

    public function close(int $boxId): bool
    {
        $box = Box::find($boxId)->close();
    }
    

    //Multudio.PHP

    public static function close()
    {
        //need to update the is_open field to 0 for found Box
    }
    

    我刚接触过Laravel,我不确定上述代码是否可行。 如果你能帮助我,我将不胜感激。

    事先谢谢。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mozammil    7 年前

    你不需要它是静态的。以下内容应使其工作:

    public function close()
    { 
        return $this->update([
            'is_open' => 0
        ]);
    }
    

    或 您可以在控制器中执行此操作:

    public function close(int $boxId): bool
    {
        $box = Box::findOrFail($boxId);
    
        return $box->update([
            'is_open' => 0
        ]);
    }
    

    findOrFail() 会扔 ModelNotFoundException 如果找不到盒子。

        2
  •  0
  •   Jignesh Joisar    7 年前

    你可以通过拉拉维尔雄辩 local scope

    本地范围允许您定义 可以很容易地在整个应用程序中重复使用。例如,您可以 需要经常检索所有被认为是“流行”的用户。 要定义范围,请在雄辩的模型方法前面加上范围

    在里面 模型PHP

    public  function scopeClose($query,$flag)
    {
        $query->where('is_open',$flag ?? 0);
        //need to update the is_open field to 0 for found Box
    }
    
    推荐文章