Reputation: 997
I have 20 records in my SQL table. I want to take the first 10 records (0-10) for the sender_id then skip and take the last 10 records (10-20) for the receiver_id
public function definition()
{
return [
'sender_id' => User::limit(10)->inRandomOrder()->get()->first()->id,
'receiver_id' => User::skip(10)->take(10)->inRandomOrder()->get()->first()->id,
];
}
The problem is that even after defining the limit at 10 I still have records with id higher than 10 in the 'sender_id' which is supposed to be (1,2,3,4,5,6,7,8,9,10)
Upvotes: 2
Views: 4044
Reputation: 64
You can also use this method. random() is a helper function in collection laravel and returns a random item from the collection https://laravel.com/docs/8.x/collections#method-random
User::take(10)->get()->random()->id
User::skip(10)->take(10)->get()->random()->id
Upvotes: 2
Reputation: 15070
Since you only want the id of one user randomly chosen between the first 10, why not randomly skip some entries and take the first?
E.g.
public function definition()
{
return [
'sender_id' => User::skip(rand(0, 9))->first()->id,
'receiver_id' => User::skip(rand(10, 19))->first()->id,
];
}
Upvotes: 1
Reputation: 5735
It's a slightly weird definition to distinguish to "models" by their id inside the same table. To make it a bit more logical, I'd go with scopes:
class User extends Model {
public function scopeSender($query)
{
return $query->whereBetween('id', [ 1, 10 ]);
}
public function scopeReceiver($query)
{
return $query->whereBetween('id', [ 11, 20 ]);
}
}
public function definition()
{
return [
'sender_id' => User::sender()->inRandomOrder()->first()->id,
'receiver_id' => User::receiver()->inRandomOrder()->first()->id,
];
}
Upvotes: 0