I'm working on developing an application for my company, and I've been using Laravel. I needed a self-referencing BelongsToMany relationship on my user model to allow users to belong to other users. (ie AEs - Clients)
Here is my code:
$id = 6;
var_dump( "ID Queried Is: $id.", Sentry::getUser()->clients()->find($id)->toArray() );
The result of Sentry::getUser()->clients()->find($id)
causes problems because when I use relationships, it uses the wrong ID to search through the related table.
I can use Sentry::getUser()->clients->find($id)
and it returns a User with the ID specified, but I can't eager load any relations to that model (that I'm aware of).
Does a BelongsToMany relationship (eg Sentry::getUser()->clients()
) query the result set by the Primary Key on the pivot table rather than by the named key ( client_id
), and if so, how can I get around it?
The result of this Sentry::getUser()->clients()->find($id)
is, as you can see, pretty much correct. By that I mean it fetches correct user, however it select *
so id
(and possibly other common fields) is overriden, so the result has
$client->id; // id of the pivot table
while other fields are right.
So you can either query the relation like this:
$client = Sentry::getUser()->clients()->select('users.*')->find($id);
or lazy load the relation (if you really need this) and use Collection
find()
method:
$user = Sentry::getUser()->load('clients');
$client = $user->clients->find($id);
// or one line, not recommended:
$client = Sentry::getUser()->load('clients')->clients->find($id);
Otherwise just use what you tried:
$client = Sentry::getUser()->clients->find($id);
You could try with this but I don't know if it will work for you and if it's what you want to achieve:
$users = Sentry::getUser()->with(array('clients' => function($q) use($id)
{
$q->whereId($id);
}))->get()->toArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.