In a Laravel environment (v 5.7) I've two tables: films and versions related in a 1 to Many relationship defined in Models as so:
class Film extends Model {
...
public function versions() {
return $this->hasMany(Version::class);
}
}
class Version extends Model {
...
public function film() {
return $this->belongsTo(Film::class);
}
}
I want to pick a random Version of a Film and its related parent Film, so in a controller I do this:
...
use App\Film;
use App\Version;
class HomeController extends Controller {
...
public function index() {
$rndVersion = Version::inRandomOrder()->first();
$relatedFilm = $rndVersion->film->first();
All works fine, except the fact that the returned film is always the first of the entire recordset, and not the parent of the version I previously loaded from the DB.
I've tried to retrieve all together with:
$rndVersion = Version::inRandomOrder()->with('film')->first();
and it works, but it packs all in a single object stored in $rndVersion, and I'd rather prefer to keep the two things separate.
So, what am I doing wrong? What shall I generally do to get the parent record of a selected/loaded one?
Thank you in advance.