0

I have two queries that return a collection. But with different ids I get different array indexes.

$worker = Worker::find($worker_id);
$man = $worker->managers->where('id', $manager_id)->first();
$tasks = $man->tasks->where('worker_id', $worker_id);
dd($tasks->toArray());

When I run this query with $worker_id of 1, I get an array with numeric index starting from 0:

[
 {
   "id": 1,
   "task_name": "Cleaning"
 },
 ....
]

But with $worker_id of 2, I get an array with named (string) indexes starting from "9":

[
 "9": {
   "id": 18,
   "task_name": "Staff reorientation"
 },
 "10": {
   "id": 19,
   "task_name": "Schedule"
 }
 ....
]

What may be the cause?

4
  • please add output here. Commented Aug 17, 2018 at 10:41
  • Added the output example. Commented Aug 17, 2018 at 10:48
  • 1
    türk olduğunu düşünerek türkçe yazıyorum, sorunun kaynağını bilmiyorum ancak array_values() metodunu kullanarak düzeltebilirsin. ayrıca tek bir sorgu ile yukarıdaki verileri çekebilirsin, ayrı ayrı her biri için istek atma gereksiz, ki muhtemelen bunu foreache sokuyorsan her ilişki için veritabanına istek atacak, sunucuyu çok yorabilir. Commented Aug 17, 2018 at 11:47
  • Tek sorguya dönüştürülmüş örnek yazabilir misin? Teşekkürler. Commented Aug 17, 2018 at 12:18

1 Answer 1

1

Filtering a collection doesn't change the original keys. You can reset them with values():

$tasks = $man->tasks->where('worker_id', $worker_id)->values();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.