Getting relations from a model

When you define relations in Eloquent models, you have an easy way of getting the related objects.
Here is a sample:

Route:

$app->get('/semester/{semester}', function ($request, $response, $args) use ($app) {
    $semester = Semester::with('seminars', 'pcuser')
       ->select('*')
       ->where('active', 1)
       ->where('id', $args['semester'])
       ->first();

    var_dump('<pre>', $semester, '</pre>');

    if ($semester !== null) {
       var_dump($semester->seminars);
    }

    return $response;
});

Notice:

$semester = Semester::with('seminars', 'pcuser')
   ->select('*')
   ->where('active', 1)
   ->where('id', $args['semester'])
   ->first();

It is more or less asking to get from the Semester model also the relations seminars and pcuser.

Let's look how that is defined in the Semester model:

public function pcuser()
{
   return $this->hasOne('Db\Eloquent\User\Model', 'id', 'pcuser');
}

and:

public function seminars()
{
  return $this->hasMany('Db\Eloquent\Seminar\Model', 'semester', 'id')
       ->where('active', 1);
}

Notice:

$this->hasMany('Db\Eloquent\Seminar\Model', 'semester', 'id')

which means that the models are linked the following way:

And notice:

->where('active', 1);

which allows you to add filtering in the set that you want back from the query.

Tip

You could also have more than one 'seminars' method on the Semester model, like:

public function seminars_all()
{
  return $this->hasMany('Db\Eloquent\Seminar\Model', 'semester', 'id');
}

public function seminars_deleted()
{
  return $this->hasMany('Db\Eloquent\Seminar\Model', 'semester', 'id')
       ->where('active', 0);
}

Now you could get you semesters query with deleted seminars like this:

$app->get('/semester/with-deleted-seminars/{semester}', function ($request, $response, $args) use ($app) {
    $semester = Semester::with('seminars_deleted')
       ->select('*')
       ->where('active', 1)
       ->where('id', $args['semester'])
       ->first();

    var_dump('<pre>', $semester, '</pre>');

    if ($semester !== null) {
       var_dump($semester->seminars);
    }

    return $response;
});

This will get the active Semester records, with the deleted Seminars on this semester record (active = 0).

Last update: Tue, 13 Sep 2022 14:32:15