Laravel合并Eloquent结果和数组

时间:2015-02-04 21:16:47

标签: php laravel eloquent

我试图合并雄辩的结果和数组,因为我需要添加用户可以用于此模型的所有可能的过滤器。如果有人知道怎么做,我真的会非常感激。这是一个示例代码:

<?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;
    }

结果非常有趣:

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

)

1 个答案:

答案 0 :(得分:1)

如果您只想在JSON响应中同时发送filtersschool_data,可以这样做:

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

或者如果您想使用array_merge

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

修改

如果您只是将数据注入到视图中,我认为没有理由合并数据,只需传递两个变量!

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

(此处$filters显然只有array('name' => 'Neshtoto')而不是包括'filters' => ...在内的完整内容