Laravel将参数从控制器传递给Model

时间:2014-09-26 11:47:37

标签: laravel laravel-4 eloquent

我是laravel的新手,我试图将参数从控制器中的函数传递给模型中的函数。我这样做了:

我的控制器

class DashBoardController extends BaseController {
    public function yesterdayOrderData(){
        $from = date('Y-m-d H:i:s', strtotime('today -1 days'));
        $to = str_replace("00:00:00", "23:59:59", $from);
        $odata = Invoice::yesterdaysorderdetails($from, $to);
    }

}

我的模特:

class Invoice extends Eloquent{
    protected $table = 'Inf_Invoice';
    public function scopeyesterdaysorderdetails($from, $to){
        echo $from."--".$to;
    }
}

我收到错误消息"Object of class Illuminate\\Database\\Eloquent\\Builder could not be converted to string"

如何将控制器中的参数传递给模型?

2 个答案:

答案 0 :(得分:1)

范围要求query实例为第一个参数(它会自动传递给函数):

// you don't need to use camelCase, but it's soooo hard to read this otherwise..
public function scopeYesterdaysOrderDetails($query, $from, $to){
     $query->whereBetween('created_at', [$from, $to]);
}


// usage:
$odata = Invoice::yesterdaysOrderDetails($from, $to)->get();

只是关于方法名称的说明 - 它应遵循一条规则 - scope部分之后的第一个字母应为大写

答案 1 :(得分:0)

您应该将您的功能名称从scopeyesterdaysorderdetails更改为yesterdaysorderdetails。似乎scopes are special functions并且他们只使用一个参数$query,这可能是Eloquent Builder,这就是你得到这个错误的原因。

在您的情况下,您只想显示以--分隔的2个日期,因此您不需要范围函数,只有普通函数不能以scope开头我认为