27

I have a controller where I want to combine data from multiple tables with parallel structures. What I want to end up with in the end is one object I can return from the controller so I can parse it in Backbone.

I want to do something like this:

public function index()
{
    $mc = MainContact::where('verified', '=', '1')->get();
    $sm = SendMessage::where('verified', '=', '1')->get();

    $obj = (object) array_merge((array) $mc, (array) $sm);
    return $obj;
}

I'm told by another post on StackOverflow that this works in PHP 5.3+. However, this returns the following error in Laravel:

UnexpectedValueException: The Response content must be a string or object implementing
 __toString(), "object" given.

How do I implement this method in Laravel? Both $mc and sm return valid objects in Laravel.

4

5 回答 5

48

现在你可以使用

$new_collection = $collection->merge($other_collection).

这在Laravel 4中有效,并且似乎可以处理数组和集合。

于 2013-10-24T13:09:13.573 回答
33

您可以在这里做的是合并两个查询结果的数组,然后使用带有 json 输出的响应,如下所示。

$array = array_merge($mc->toArray(), $sm->toArray());
return Response::json($array);
于 2013-01-11T21:00:24.763 回答
9

我们可以使用如下集合

$admins = User::where('type', '=', 'admin')->get();

$authors = User::where('type', '=', 'author')->get();

$admin_author_collection = $admins->merge($authors);

另外,请参考以下链接的各种收集方法

http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html

于 2014-10-17T06:39:29.407 回答
3
Route::get('test', function(){
    $rank = Rank::get();
    $policy = Policy::get();
    $obj = (object)array_merge_recursive((array)$rank , (array)$policy);
    var_dump($obj);
});

这对我有用。代替 array_merge 使用 array_merge_recursive()。

于 2014-02-02T17:59:37.417 回答
-3

你可以简单地使用array_merge(firstObject,secondObject)函数。

$obj = array_merge($mc, $sm);
return $obj;
于 2019-09-09T10:26:58.770 回答