evanr evanr - 2 years ago 113
MySQL Question

Fetch related items ordered randomly with eloquent / Larvael 5.x

Simply put, if I have an Entity that has many related items (hasMany) how can I fetch that entity and it's related items with those related rows being ordered randomly

I fetch like so:

$question = Question::with('categories', 'answers')->where( _some_parameters_ ) ... ->get();

How would I shuffle those 'answers' in the resulting object?

Answer Source

You could try something like this:

$question = Question::with(['categories', 'answers' => function($q) {
}])->where( _some_parameters_ )

This is only for MySQL though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download