Laravel 5使用where子句实例化模型

时间:2016-01-19 18:30:50

标签: php laravel-5.2

在我的控制器中,我希望能够调用模型Category并给它一个数组('dbField'=>'value'),我希望能够在where子句中使用这个数组。

我的控制器:

$categories = new Category(['name' => 'category name']);

我的模特:

public function __construct($attributes = [])
{
  parent::__construct($attributes);
...
}

但它似乎没有那样工作,每当你将属性传递给模型构造函数时,它只是为了大规模的分配,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

构造函数用于填充属性。

您可以尝试实际的地方

$attributes = ['name' => 'blah'];

$findIt = Category::where($attributes)->get(); // or first();

// get the first matched record based on the attributes or return a new instance filled with those attributes
$findItorNot = Category::firstOrNew($attributes);