Laravel关系是缓慢的

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

我尝试运行这段代码

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

但这么慢我的数据库有1M以上的记录。

paroduct_saves表:enter image description here

谢谢

laravel laravel-5 laravel-4 eloquent laravel-5.2
2个回答
0
投票

你的桌子上像这样创建索引:

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

0
投票

下面添加在您的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);
© www.soinside.com 2019 - 2024. All rights reserved.