laravel 具有多个参数的 Laraver FindOrNew

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30929696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:48:22  来源:igfitidea点击:

Laraver FindOrNew with multiple parameters

phplaravellaravel-5eloquent

提问by raphadko

I'm using laravel FindOrNew() to get an entry with two parameters, or create a new one:

我正在使用 laravel FindOrNew() 来获取带有两个参数的条目,或者创建一个新的条目:

$option = \App\Option::findOrNew(['user_id' => $this->id , 'option_name' => $optionName]);

I want to get an option for a user that has the name in $optionName. The problem is that it just checks for the user_id, and does not create a new one when option_name does not exist.. instead it "finds" one which does not match the $optionName value..

我想为名称在 $optionName 中的用户获得一个选项。问题是它只检查 user_id,并且在 option_name 不存在时不会创建一个新的。相反,它“找到”了一个与 $optionName 值不匹配的值。

Can someone say what I'm doing wrong? How can I achieve this?

有人可以说我做错了什么吗?我怎样才能做到这一点?

回答by patricus

TL;DR:

特尔;博士:

You're using the wrong method. You're looking for the firstOrNew()method, not findOrNew().

你使用了错误的方法。您正在寻找firstOrNew()方法,而不是findOrNew()

Explanation:

解释:

The findOrNew()is an extension of the find()method, which works on ids only. It takes two parameters, the first being the id (or array of ids) to find, and the second being the columns to retrieve. It's treating the array you've passed in as an array of ids to find.

findOrNew()是的扩展find()方法,该方法仅适用IDS。它需要两个参数,第一个是要查找的 id(或 id 数组),第二个是要检索的列。它将您传入的数组视为要查找的 id 数组。

The firstOrNew()method takes one parameter: an array of attributes to search for. It will turn the array into a where clause, and then call first()on the query builder. If no results are returned, it returns a new instance with those attributes filled in.

firstOrNew()方法采用一个参数:要搜索的一组属性。它会将数组转换为 where 子句,然后调用first()查询构建器。如果没有返回结果,它会返回一个填充了这些属性的新实例。