Laravel toArray() 仍然在 DB::raw 中返回一个对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41447275/
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 15:03:09  来源:igfitidea点击:

Laravel toArray() still returning an object in DB::raw

phparrayslaravel

提问by PinoyStackOverflower

I have this code:

我有这个代码:

 $response['data'] = DB::table('customers')
                ->select(DB::raw('name,email,address1,address2,postalcode,state_region,country_code,phone,created_at'))
                ->where('user_id',"=",Auth::user()->id)
                ->where('name','like',"%$search_value%")
                ->orWhere('address1',"%$search_value%")
                ->orWhere('email','like',"%$search_value%")
                ->orWhere('address2','like',"%$search_value%")
                ->orWhere('city','like',"%$search_value%")
                ->orWhere('postalcode','like',"%$search_value%")
                ->orWhere('state_region','like',"%$search_value%")
                ->orWhere('country_code','like',"%$search_value%")
                ->orWhere('phone','like',"%$search_value%")
                ->orderBy('name', $order)
                ->limit($length)
                ->offset($start)
                ->get()->toArray();

The result of this one is this:

这个结果是这样的:

'data' => 
    array (size=10)
      0 => 
        object(stdClass)[194]
          public 'name' => string '|Barbara User' (length=13)
          public 'email' => string '[email protected]' (length=16)
          public 'address1' => string 'address aaddress' (length=17)
          public 'address2' => null
          public 'postalcode' => string '00000000' (length=10)
          public 'state_region' => string 'GA' (length=2)
          public 'country_code' => string 'US' (length=2)
          public 'phone' => string '12312312312' (length=10)
          public 'created_at' => string '2017-01-02 15:20:20' (length=19)
      1 => 
        object(stdClass)[201]
            public 'name' => string '|Barbara User' (length=13)
          public 'email' => string '[email protected]' (length=16)
          public 'address1' => string 'address aaddress' (length=17)
          public 'address2' => null
          public 'postalcode' => string '00000000' (length=10)
          public 'state_region' => string 'GA' (length=2)
          public 'country_code' => string 'US' (length=2)
          public 'phone' => string '12312312312' (length=10)
          public 'created_at' => string '2017-01-02 15:20:20' (length=19)
    ....

As you can see, there is still an object in the result even if I already did a toArray().

如您所见,即使我已经做了一个toArray().

What seems to be the problem here?

这里似乎有什么问题?

Your help will be greatly appreciated! Thanks!

对你的帮助表示感谢!谢谢!

回答by patricus

When you call toArray()on a Collection, if the underlying items implement the Illuminate\Contracts\Support\Arrayableinterface, the collection will attempt to call toArray()on each item. However, when you use the query builder, the result will be a Collectionof stdClassobjects, and stdClassobjects are plain objects that do not implement that interface and do not have a toArray()method. Therefore, when you call toArray()on a Collectionof stdClassobjects, you will just get a plain array of the stdClassobjects back.

当您调用toArray()a 时Collection,如果基础项实现该Illuminate\Contracts\Support\Arrayable接口,则集合将尝试调用toArray()每个项。但是,当您使用查询生成器,其结果将是一个CollectionstdClass对象,stdClass对象是不实现该接口并没有一个简单的对象toArray()方法。因此,当你调用toArray()a CollectionofstdClass对象时,你只会得到一个简单的stdClass对象数组。

If you instead use Eloquent, define a Customermodel, and use that model to perform the query, your result will be a Collectionof Customermodels, and those models do implement the Arrayableinterface. So, when you call toArray()on this Collection, it will call toArray()on each item in the Collection, and your result will be an array of arrays.

如果改用口若悬河,定义了一个Customer模型,并使用该模型来进行查询,您的结果将是一个CollectionCustomer模型,这些模型做实现Arrayable接口。因此,当您调用toArray()this 时Collection,它将调用toArray()中的每个项目Collection,您的结果将是一个数组数组。

If, for some reason, you don't want to use Eloquent, you will need to manually convert the items from objects to arrays. You can do this easily with the mapor transformmethods on the Collection. Use mapif you want to return a new Collectionand leave the original one alone, or use transformif you just want to modify the original Collection.

如果出于某种原因,您不想使用 Eloquent,则需要手动将项目从对象转换为数组。您可以使用 上的maptransform方法轻松完成此操作Collection。使用map,如果你想返回一个新的Collection,并独自离开原来的一个,或使用transform,如果你只是想修改原始Collection

$response['data'] = DB::table('customers')  
    // query conditions, etc
    ->get()
    ->map(function ($item, $key) {
        return (array) $item;
    })
    ->all();

回答by DevK

You are converting the collection to array, not each model specifically.

您正在将集合转换为数组,而不是每个模型。

You could do something like this using Laravel's collection ->transform()method:

你可以使用 Laravel 的 collection ->transform()方法做这样的事情:

    $response['data'] = DB::table('customers')
            ->select(DB::raw('name,email,address1,address2,postalcode,state_region,country_code,phone,created_at'))
            ->where('user_id',"=",Auth::user()->id)
            ->where('name','like',"%$search_value%")
            ->orWhere('address1',"%$search_value%")
            ->orWhere('email','like',"%$search_value%")
            ->orWhere('address2','like',"%$search_value%")
            ->orWhere('city','like',"%$search_value%")
            ->orWhere('postalcode','like',"%$search_value%")
            ->orWhere('state_region','like',"%$search_value%")
            ->orWhere('country_code','like',"%$search_value%")
            ->orWhere('phone','like',"%$search_value%")
            ->orderBy('name', $order)
            ->limit($length)
            ->offset($start)
            ->get();

    $response['data']->transform(function ($item) {
        // return $item->toArray(); // You could do this if you called the query with model
        return (array)$item; // This should work in your case 
    });

This way $response['data'] will be a collection (not array) of arrays. You could additionally do this:

这样 $response['data'] 将是数组的集合(不是数组)。您还可以这样做:

$response['data']->toArray();

To convert the collection to array as well.

将集合也转换为数组。

回答by Amit Gupta

You can type cast each object in the collection to an array as:

您可以将集合中的每个对象类型转换为数组:

$response['data']->transform(function($x) {
   return (array) $x; 
})->toArray();

And the toArraygets you from the collection back to an array.

然后toArray让你从集合回到数组。