在laravel中从db获取数据时允许的内存错误

问题描述 投票:0回答:2

我正在尝试从数据库中获取所有帖子并在视图中显示。我想要的帖子使用post_type = product存储在数据库中。

我收到了这个错误:

Allowed memory size of 134217728 bytes exhausted (tried to allocate 62918656 bytes)

这是我的模特:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class GetPostModel extends Model
{
    /**
     * @param $filed
     * @param $value
     * @return mixed
     */
    static function get_posts_by_filed($filed, $value)
    {
        $result = DB::table('posts')->where($filed, $value);
        return $result;
    }
}

这就是我在Controller中所做的:

public function all_products_page(Request $request)
{

    //getting the products
    $all_products = GetPostModel::get_posts_by_filed('post_type', 'product');
    echo '<pre>';
    print_r($all_products);
    echo '</pre>';
}
php laravel laravel-5.5
2个回答
1
投票

发生这种情况是因为你缺少get()

public function all_products_page(Request $request)
{

//getting the products
$all_products = GetPostModel::get_posts_by_filed('post_type', 'product')->get();
echo '<pre>';
print_r($all_products);
echo '</pre>';
 }

0
投票

您的数据库中似乎有太多条目,它们都被加载到PHP内存中。

简单的解决方案是增加PHP内存限制:

ini_set('memory_limit', '512M');

正确的解决方案是尝试保护您的内存使用并限制一次处理所有信息。另外,请记住,向浏览器发送过多信息也可能会影响客户端的性能。

一种可能的方法是使用分页。 Laravel已将此集成在查询构建器中:https://laravel.com/docs/5.6/pagination

如果绝对需要通过所有帖子,您可能需要按照Eloquent文档中的描述来分块结果:https://laravel.com/docs/5.6/eloquent#chunking-results

此外,更像Laravel的方法看起来像这样:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $table = 'posts';

    /**
     * Scope a query to only include products
     *
     * @param \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeProducts($query)
    {
        return $query->where('post_type', 'product');
    }
}

然后,您的Controller将如下所示:

<?php

public function all_products_page(Request $request)
{

    Post::products()->chunk(100, function ($products) {
        foreach ($products as $product) {
            // perform action here.
        }
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.