简体   繁体   English

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

[英]Laravel 5 instantiate model with where clause

In my controller, I want to be able to call the model Category and give it an array ('dbField' => 'value') and I want to be able to use this array in a where clause. 在我的控制器中,我希望能够调用模型Category并为其提供一个数组('dbField'=>'value'),并且希望能够在where子句中使用此数组。

My Controller: 我的控制器:

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

My Model: 我的模特:

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

But it doesn't seem to work that way, whenever you pass attributes to the model constructor it's only for mass assignement, is there any way to do that ? 但这似乎不起作用,每当您将属性传递给模型构造函数时,它仅用于批量分配,有没有办法做到这一点?

The constructor is for filling attributes. 构造函数用于填充属性。

You can try an actual 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM