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

Laravel 5 instantiate model with where clause

在我的控制器中,我希望能够调用模型类别并为其提供一个数组 ('dbField' => 'value'),并且我希望能够在where 子句。

我的控制器:

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

我的模特:

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

但它似乎并没有那样工作,每当你将属性传递给模型构造函数时,它只是为了批量赋值,有什么办法可以做到这一点吗?

构造函数用于填充属性

你可以试试实际的where

$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);