John Davidson

php - Why query result suddenly changed after called from other medthod in Laravel

0 comments
Message:


I have problem here with query result from Eloquent, I tried to query from DB and put in variable $contractList in my mount() method and the result as expected. But when I tried to retrieve specific data from $contractList with $contractList->find($id), the result not same as in mount() method.


Here is query from mount():


public function mount(){
$contractList = Kontrak::select(['id', 'mou_id'])->with(['order:id,kontrak_id', 'order.worklist:id', 'order.worklist.khs:id,mou_id,worklist_id,khs', 'amdNilai:id,kontrak_id,tgl_surat'])->withCount('amdNilai')->get()
}

Here the result:


But when I tried to find specific data from $contractList, properties that shown not same as in mount:


    public function itemSelected($id)
{
//amd_nilai_count not showing
$kontrak = $this->contractList->find($id);
if ($kontrak->amd_nilai_count == 1) {
$this->nilai_amd = $this->calculateNilai($id);
}
}

Here is the result called from itemSelected():


I have tried use get() but the result still problem, how to get same properties same as in mount().By the way im use laravel & livewire.



My Answer:
>find($id) in other method, the result suddenly changed. Can anyone explain why this happened?

This issue may be caused by the way Eloquent handles query results and relationships. When you retrieve data from the database using Eloquent, it returns a collection of model instances. These model instances are stored in memory and any changes made to them will affect the original query result.

When you call the `find($id)` method on the `$contractList` collection, Eloquent will search for the model instance with the specified ID within the collection. If the model instance is found, it will return that specific model instance, which may have been modified or updated since the original query was executed.

To avoid this issue, you can use the `fresh()` method to retrieve a fresh copy of the model instance from the database, ensuring that you are working with the most up-to-date data. Alternatively, you can re-query the database to get the specific data you need, rather than relying on the original query result.

Overall, it's important to be aware of how Eloquent handles query results and model instances to avoid unexpected behavior when working with data in Laravel.

Rate this post

3 of 5 based on 7326 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us