bohdan baida bohdan baida -4 years ago 166
MySQL Question

Laravel relations, select next raleted row from database.

I have related items in my database. I selected all of items from database by related id:

$next_stock = $this->model->get()->where('part_id', $in_data['part_id'])->all();


and I collection of rows grouped by one specific id, like on the picture. All of them selected by "part_id":

Selection Of Items

Grouped By Same Id

Also with this line of code i can select one of the items from this collection:

$next_stock = $this->model->get()->where('id', $old_stock['id'])->where('part_id', $in_data['part_id'])->first();


But how can I select the following items after this one?
Or, how can I select second or third item from this collect?

I cannot just increase id number by one from first, because sometimes this item ids not following each other.

Answer Source

Having a collection, you can take a specific element in the position with a combination of take() and last().

$collection = $this->model->get()->where('part_id', $in_data['part_id'])->all();
$second = $collection->take(2)->last(); //if this doesnt work, do it in 2 steps
$third  = $collection->take(3)->last(); //if this doesnt work, do it in 2 steps

If you don't have a collection, take directly from database like this

$second = $this->model
->where('part_id', $in_data['part_id'])
->skip(1)
->first(); 

If it doesn't work with first()

$collect = $this->model
->where('part_id', $in_data['part_id'])
->skip(1)
->take(1)
->get();

$second = $collect->first();

Edit

skip() and take() are actually part of the query builder, not eloquent model. So it won't work with Eloquent in Laravel 5.4

Try with

$collect = $this->model
->where('part_id', $in_data['part_id'])
->get(1); //For the second record, 0 being the first
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download