Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在laravel雄辩选择上添加额外条件_Php_Laravel_Eloquent - Fatal编程技术网

Php 在laravel雄辩选择上添加额外条件

Php 在laravel雄辩选择上添加额外条件,php,laravel,eloquent,Php,Laravel,Eloquent,我的系统中几乎每个表都有一个字段id\u unity,用于控制注册表来自哪个unity 我想知道是否有可能将->get()和->lists()方法从eloquent更改为add ->where('id_unity',Session::get('unity'); 在每次选择之前,我只需执行以下操作: Products::all(); //and that actually will be Products::where('id_unity',Session::get('unity'))

我的系统中几乎每个表都有一个字段
id\u unity
,用于控制注册表来自哪个unity

我想知道是否有可能将
->get()
->lists()
方法从eloquent更改为add

->where('id_unity',Session::get('unity'); 
在每次选择之前,我只需执行以下操作:

Products::all(); //and that actually will be 
Products::where('id_unity',Session::get('unity'));

有人吗?;)

您可以使用查询范围:

public function scopeGetAll($query)
{
   return $query->where('id_unity', Session::get('unity'))->get();
}
然后静态调用它,不使用“scope”前缀:

如果您想让它对所有模型都可用,只需创建一个模型扩展的基本模型类,您可以在其中定义该函数

Base.php

use Illuminate\Database\Eloquent\Model;
use Session;

class Base extends Model {

    public function scopeGetAll($query)
    {
       return $query->where('id_unity', Session::get('unity'))->get();
    }    
}
Products.php

use Base;
class Products extends Base {

}

请查看全局scopesPerfect!!!!工作正是我所需要的!只需等待4分钟就可以选择您的答案!非常感谢;)
use Base;
class Products extends Base {

}