【问题标题】:Laravel relationship is slowLaravel 关系很慢
【发布时间】:2019-07-03 18:20:14
【问题描述】:

我尝试运行这段代码

Item::with('product_save')->whereHas('product_save', function($q){ 
    $q->where('user_id', 4);
});

paginate(20);

物品型号:

    class Item extends Model
{
    protected $table = 'products';

    public function product_save()
    {
        return $this->hasOne('App\Product_save','product_id')->where('user_id', Auth::user()->id);
    }
}

但是太慢了,我的数据库有超过 100 万条记录。

paroduct_saves 表:

谢谢

【问题讨论】:

  • 尝试使用分页获取数据
  • 您可能没有正确设置索引。在使用 EXPLAIN 之前向我们展示您的 SQL 查询。
  • 我用 paginate(20);但是太慢了。
  • 只选择重要的字段肯定会减少执行时间
  • @Marwelln 我如何向您展示 SQL?我没有在数据库中设置任何索引只是主键

标签: laravel laravel-5 laravel-4 eloquent laravel-5.2


【解决方案1】:

像这样在你的表上创建索引:

CREATE INDEX index_name
ON table_name (column1, column2, ...);

【讨论】:

  • 用于主键?
  • 如果您选择user_id 添加user_id 例如:CREATE INDEX index_user on table_name (user_id)
  • 谢谢,但还是很慢。查询需要 2 秒: select * from products where exists (select * from product_saves where products.id = product_saves.product_id and user_id = 2) 我有超过 60k 条记录
【解决方案2】:

在您的 ProductSave 模型中添加以下关系:

use Illuminate\Database\Eloquent\Model;
class ProductSave extends Model
{
    protected $table='product_saves';
    public $primaryKey='id';


         public function product(){
         return $this->belongsTo('App\Product','product_id')->where('active',1);
    }

}

现在在你的控制器中试试这个:

$products=ProductSave::where('user_id',4)->with('product')->paginate(20);

【讨论】:

  • 谢谢,但我在 $products = $products->where('active', 1); 项中添加了相同的条件怎么添加?
  • 查询耗时 2 秒:select * from products where exists (select * from product_saves where products.id = product_saves.product_id and user_id = 2)。因为我有超过 6 万条记录
  • 我需要添加很多条件,所以我需要像 Product::has('product_save') 这样使用。添加条件简单::where()
  • @cha7ta,你想要什么?请详细描述
  • 我想在 product_saves 中选择多个选项 price created_at updated_at 卖家名称的商品...所有这些条件都在 product_saves 中的 user_id =2 或 3 的商品中......
猜你喜欢
  • 1970-01-01
  • 2014-07-10
  • 1970-01-01
  • 2018-06-06
  • 2013-05-09
  • 2019-11-11
  • 1970-01-01
  • 2015-08-05
  • 2016-10-12
相关资源
最近更新 更多