简体   繁体   English

Laravel合并雄辩的结果和数组

[英]Laravel merging Eloquent result and array

I'm trying to merge eloquent result and array because I need to add all possible filters that user can use for this model. 我正在尝试合并雄辩的结果和数组,因为我需要添加用户可以用于此模型的所有可能的过滤器。 If anyone have any other idea how to make it I really would be very thankful. 如果有人对如何实现有其他想法,我将非常感谢。 Here is an example code: 这是示例代码:

<?php

class School extends Eloquent {
    protected $table = 'schools';

    public function listSchoolsEndUser()
    {
        $schools_data = new School;

        $schools_data = $schools_data->paginate(12);

        $filters = array( 
            'filters' => array(
                'name' => 'Neshtoto'
            )
        );

        $schools_data = (object) array_merge(get_object_vars($schools_data), $filters);

        echo '<pre>';
        print_r( $schools_data );
        exit;

        return $schools_data;
    }

And the result is very interesting: 结果非常有趣:

stdClass Object
(
    [filters] => Array
        (
            [name] => Neshtoto
        )

)

If you just want to send both, filters and the school_data back in a JSON response you can do it this way: 如果您只想将filtersschool_data都发送回JSON响应中,则可以通过以下方式进行操作:

return Response::json(array(
   'filters' => array(
        'name' => 'Neshtoto'
    ),
    'data' => $school_data->toArray()
));

Or if you want to use array_merge : 或者,如果您想使用array_merge

$school_data = array_merge($filters, array('data' => $school_data->toArray()));
return $school_data;

Edit 编辑

If you are just injecting the data into a view I see no reason at all to merge the data, just pass two variables! 如果您只是将数据注入视图中,那么我完全没有理由合并数据,只需传递两个变量即可!

return View::make('view', array('schools' => $school_data, 'filters' => $filters));

(Here $filters would obviously only be array('name' => 'Neshtoto') and not the full thing including 'filters' => ... ) (这里$filters显然只会是array('name' => 'Neshtoto')而不是包括'filters' => ...在内的全部内容'filters' => ...

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

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