So to get the related entities, you have a couple options:
- You can add
->with('member')
to your Sprunje’s query to eager-load the related entity. Keep in mind that if you do this, you’ll have to access the fields in this table via the member
relation. You’ll also have to add custom filters in your Sprunje and use a whereHas
closure to be able to filter on these fields;
- You can use a global scope to automatically join the
user
table fields whenever you access a Member
object. This is basically what the scopeJoinUser
does, except it is automatically applied to any queries off the Member
model. This is probably my favorite approach, and I actually use it to join our workers’ account balances when we retrieve them:
<?php
/**
* Bloomington Tutors
*
* @link https://bitbucket.org/bloomingtontutors/btoms
* @license All rights reserved
*/
namespace UserFrosting\Sprinkle\Btoms\Database\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class AccountScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
// Determine the type of entity that has this account
$morphType = $model->getMorphClass();
$primaryKeyName = $model->getQualifiedKeyName();
$table = $model->getTable();
$builder->addSelect("$table.*", 'accounts.balance as balance');
// Join on matching primary accounts
$builder->leftJoin('accounts', function ($join) use ($primaryKeyName, $morphType) {
$join->on('accounts.accountable_id', '=', $primaryKeyName)
->where('accounts.accountable_type', '=', $morphType)
->where('accounts.type', '=', 'primary');
});
}
}
You’ll notice that in this example, we dynamically decide which table to join on, because there are multiple types of entities that could have accounts. Once you have this scope defined, you need to boot it in your Member
model:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::addGlobalScope(new AccountScope);
}
So, you’d probably do something similar, joining on your members
table. I might actually change the documentation to recommend this global scope approach over the local scopeJoinUser
approach.
The other thing we’re working on is support for properties
in Sprunjes. So, you’d be able to specify properties[]=
in a request to automatically load relations in a Sprunje.