Just out of interest, because I can work around it, does anyone know why with
doesn’t filter items to match a newly created model? Let me explain.
I have a model with the following relationship on my Transaction model.
public function splits()
{
return $this->hasMany(Split::class, 'trans_id', 'trans_id');
}
Given a transaction with an $id,
Transaction::where('id', $id)->with('splits')->get()
correctly returns only the splits related to transaction with $id.
Transaction::find($id)->with('splits')->get()
on the other hand returns all splits. I understand this is because find
is left until last in eloquent’s processes. That’s strange to me, but I’ve learned to live with it.
Even stranger, now, is that if I create a transaction and associated split
$t = Transaction::create(data);
$s = Split::create(['transaction_id' => $t->id]);
and try to eager load the relationship
$t->with('splits')->get()
once again returns all splits in the database, rather than filtering for matches with $t.
I can work around this with
Transaction::where('transaction_id', $t->id)->with('splits')->get()
but I’d love to know why the simpler version doesn’t work.