You can use the cursor() method to optimize your query. The cursor() method will return a cursor instance which can be used to iterate over the results. You can use the whereHas() method within the cursor() method to filter the results. Here is an example:
Product::cursor()
->whereHas('supplier', function (Builder $query) {
$query->where('sys_state','!=','-1');
})
->whereHas('customer', function (Builder $query) {
$query->where('sys_state','!=','-1');
})
->where('sys_state','!=','-1')
->with('supplier')
->orderBy('id','desc')
->each(function ($product) {
// Do something with the product
});
The cursor() method is more efficient than the chunk() method when dealing with large datasets. The chunk() method will load the entire dataset into memory, while the cursor() method will only load one record at a time.