#How to Order result by hasManyThrough relationship?

11 messages · Page 1 of 1 (latest)

hardy veldt
#

I have three classes:
Block (has no relationships columns)
Element (has block_id)
Atom (has element_id)

As I see I can get Block's Atmos by making this relationship:
return $this->hasManyThrough(Atom::class, Element::class, 'block_id', 'element_id');

But what I need to do it so make query with getting all the blocks which has at least one atom insite any of their elements.

And after that I want to order Blocks by created_at Atom column with this Atom parameters.

It should be like that:

  1. Block #1028
    • Atom - created_at 14/05/2023 ...other columns
  2. Block #531
    • Atom - created_at 16/05/2023 ...other columns
stone hedge
#

you could use a closure in your sortBy to sort it

#

actually you can use ->latest() with this

hardy veldt
stone hedge
#

waitwait

#
Block::all()->sortBy(function ($block) {
  return $block-atom->created_at;
});
#

that is the sortBy method

hardy veldt
#

@stone hedge But my Block hasMany Atoms.

stone hedge
#

Hmm...

#

actually, I think you need to do it in your templates, you can do

@foreach ($blocks as $block)
  @foreach ($block->atoms->latest() as $atom)
    // Do something with $atom
  @endforeach
@endforeach
hardy veldt
#

It is API, there is no visuall output