无法在Laravel中的Eloquent集合上合并 [英] Cannot merge on an Eloquent collection in Laravel
问题描述
我需要在Laravel 5.1中合并集合或数组(可以是任意一个),但在Builder.php第2071行中出现错误BadMethodCallException:调用未定义的方法Illuminate\Database\Query\ Builder :: merge()
I need to merge either a collection or an array (it can be either) in Laravel 5.1, but I am getting the error BadMethodCallException in Builder.php line 2071: Call to undefined method Illuminate\Database\Query\Builder::merge()
当我从头开始创建一个集合时,我可以将其合并,但是我无法合并到Eloquent查询的结果中,我认为也是收藏。但是也许那是不正确的?
When I make a collection from scratch, I can merge to it, but I cannot merge onto the result of an Eloquent query, which I thought were collections as well. But perhaps that is not true?
给出错误的代码:
$user=User::where('user_last_name', 'Doe')->first();
$tomerge = collect(['book' => 'desk', 'foot' => 'chair']);
$newcollect = $user->merge($tomerge);
如果我改为使用$ tomerge-> merge($ user),它可以工作,但这不是我的工作实际需要。
If I instead did $tomerge->merge($user) it works, but that's not what I actually need. Is there a way to use merge as I want?
推荐答案
要回答有关其为何不起作用的问题...
To answer your question as to why it's not working...
$user = User::where('user_last_name', 'Doe')->first();
这是模型的单个实例。不是收藏。雄辩的模型没有 merge
方法。
This is a single instance of a model. Not a collection. An eloquent model does not have the merge
method.
如果要将属性附加到雄辩的模型,则最简单的方法可能是使用 $ appends
属性和适当的访问器。例如,在您的用户模型中。
If you want to append attributes to an Eloquent model, the simplest way is probably to use the $appends
property and the appropriate accessor. For example, in your User model..
protected $appends = ['book', 'foot'];
public function getBookAttribute()
{
return 'desk';
}
public function getFootAttribute()
{
return 'chair';
}
不过,请注意,这将影响您的User模型的每个实例。
However, note that this will affect every instance of your User model.
这篇关于无法在Laravel中的Eloquent集合上合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!