我尝试运行这段代码
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以上的记录。
谢谢
你的桌子上像这样创建索引:
CREATE INDEX index_name
ON table_name (column1, column2, ...);
下面添加在您的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);