D
D
Danil Sysoev2021-01-20 15:07:40
PHP
Danil Sysoev, 2021-01-20 15:07:40

Why is the model written to the variable not working correctly?

Why after the first request, the model changes if I write it to a variable?

$this->order = MyModel::where('id', $this->id);
$foo = $this->order->where('id_user', 1)->count(); //работает
$bar = $this->order->where('id_user', 2)->count(); //не работает

After a little experiment, I realized that if I replace where with orWhere in the second line, it turns out that it remembers the first value. I do not quite understand this mechanics, who will help to understand this, and how to make sure that the model does not change? Or does each iteration need a new model object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-01-20
@YoungOldMan

As noted in the comments, there you do not have a model, but a builder.
When you call where on it, you are changing the object of that builder itself. When you call a second time, the conditions add up.
You end up with something like:
where id_user = 1 && id_user = 2
Which does not make sense in principle, because the same field cannot equal two different values ​​​​at once.
Solution: use clone

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question