strange relation behaviour?

Hi all, I'm facing is a strange behaviour I want to share with you. I have two models linked one to another by a relationship: OrderItem has many Confirms. Inside an OrderItem model method I create two Confirms and I save them. Then I use

 $confirms = $orderItem->getConfirms();

and $confirm it’s empty But if I use:

$confirms = Confirm::findByOrderItemId($orderItem->getId());  

$confirms is populated as I did. As a matter of facts if I see on the DB table Confirm I find the confirms even when I use the relationship alias function. Is it a bug? Is it a known behaviour? What am I missing about?

That’s the OrderItem relationship definition:

public function initialize(){  
        $this->setSource("OrderItem");  
        $this->hasMany(  
          'id',  
          'App\Models\Confirm',  
          'orderItemId',  
          [  
            'alias' => 'confirms',  
            'reusable' => true  
        ]);  
}  

The problem may be related to caching. To stop the DB from getting hit each time getConfirms() is called, the result is cached the first time, then referenced subsequently. when you call Confirm::findByOrder....., you're making a query separate from any existing object, so a new query gets run. I'd imagine you can turn that behaviour off, but a better approach might be to call $orderItem->refresh() instead.



2.4k

oh thank you, $orderItem->refresh()it's what I really need. I have a lot of nested operations inside my orderItem and every one alter the state of a related object. It was a pity to waste the relation alias using the query direct. When and were you suggest to run refresh?

Call refresh() after every operation that alters the state of the record in the database. That way your object will always match. However, every call to refresh() is a new call to the database.