Skip to content

Instantly share code, notes, and snippets.

@danielmorgan
Created September 3, 2016 21:41
Show Gist options
  • Select an option

  • Save danielmorgan/1ef6ee6b9b7a55129e46b43a3c99698c to your computer and use it in GitHub Desktop.

Select an option

Save danielmorgan/1ef6ee6b9b7a55129e46b43a3c99698c to your computer and use it in GitHub Desktop.
Custom relationship eager constraint problem
BadMethodCallException in Builder.php line 2431:
Call to undefined method Illuminate\Database\Query\Builder::getKeys()
<?php namespace App\Rooms;
// ...
class Room extends Model
{
use Locatable, HasCustomRelations;
// ...
public function occupants()
{
return $this->custom(
User::class,
// add constraints
function($relation) {
$relation->getQuery()
->join('locations', 'users.id', '=', 'locations.locatable_id')
->where([
['locations.locatable_type', User::class],
['locations.parent_id', $this->location->id],
]);
},
// add eager constraints
function($relation, $models) {
$relation->getQuery()->whereIn('users.id', $relation->getKeys($models));
}
);
}
}
<?php namespace App\Http\Controllers;
// ...
class RoomController extends Controller
{
public function index()
{
return \App\Rooms\Room::with('occupants')->get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment