Php 自定义查询生成器Laravel
是否可以在模型内创建自定义查询生成器并返回查询?这不是一个压力大的问题,但会有帮助Php 自定义查询生成器Laravel,php,laravel,laravel-5,Php,Laravel,Laravel 5,是否可以在模型内创建自定义查询生成器并返回查询?这不是一个压力大的问题,但会有帮助 /* Controller */ public function getOrders() { $orders = \App\Order::where('is_new', 1)->getFromUserStore(); } /* Order Model */ public function getFromUserStore() { if(\Auth::user()->store-&g
/* Controller */
public function getOrders()
{
$orders = \App\Order::where('is_new', 1)->getFromUserStore();
}
/* Order Model */
public function getFromUserStore()
{
if(\Auth::user()->store->id == 1)
{
return $this->get();
}
else
{
return $this->where('status_id', 1)->get();
}
}
谢谢我相信您正在寻找 作用域允许您定义可能需要的公共约束集 在整个应用程序中轻松重复使用
这是问题本身的一部分,但我建议您对名称空间使用
use
操作符,以避免一直使用反斜杠。对于您的控制器,您应该使用App\Order代码>并且对于您的模型使用照明\Support\Facades\Auth
@Wistar,我通常使用use
。。使用反斜杠是否存在性能问题?谢谢你的意见。我不知道性能问题。还有,答案有效吗?正是我想要的。谢谢您。
/* Controller */
public function getOrders()
{
$orders = \App\Order::where('is_new', 1)->getFromUserStore()->get();
}
/* Order Model */
public function scopeGetFromUserStore($query)
{
if(\Auth::user()->store->id == 1)
{
return $query;
}
else
{
return $query->where('status_id', 1);
}
}