bohdan baida
bohdan baida

Reputation: 389

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.

Upvotes: 1

Views: 2316

Answers (2)

EddyTheDove
EddyTheDove

Reputation: 13259

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

Upvotes: 3

Jurgen Schmidt
Jurgen Schmidt

Reputation: 46

If you aren't doing it yet, you should set your model's relationships. E.g. If you use "one-to-many", Eloquent will automatically determine the proper foreign key column on the model for you.

$parts = App\Stock::find(1)->partId;

foreach ($parts as $part) {
    //
}

Upvotes: 0

Related Questions