ORM Relationships

Hello guys i have issue here. For example I have the following tables

accounts, -> hasManyToMany providers providers, -> hasManyToMany accounts accounts_providers -> belongsTo accounts,providers

And these 3 models

Accounts.php Providers.php ProvidersAccounts.php

I made the relationships and everything is working fine, but how can i get for example all the accounts paired with provider. Currently I can take the records separately like this

$providers = Providers::findFirst();

 $providersAccounts = $providers->accounts->toArray();

I am getting only the account paired with the provider. So my question is how can i get multidimensional array together with the paired accounts. Thanks in advance

I'm a little unclear on exactly what you want, but I'm assuming you're wanting an array with all the providers, and all the accounts associated with each provider.

You'll have to build it directly. By that I mean, you'll have to ask for all providers, then iterate through all providers to get all accounts for each provider, and manually put each provider and account into one array.

My question though, is why do you need to do this? Why do you need to take the information and put it in an array? I assume you are then doing some operation with the information in the array? Why not do those same operations just on the ResultSet you get back from Providers::find()?



252

Hello, what I am trying to do here is that, i have to return all the data together as json. Eloquent have such functions btw... There is one thing i can't figure out

this is piece of code in my controller :

$providers = Providers::find()->toArray();

$providersAccounts = $providers->accounts->toArray();

This is not working... Why I can't use accounts on find(), it's only working if it's like this :

$providers = Providers::findFirst()->toArray();

$providersAccounts = $providers->accounts->toArray();

Thanks.

edited Aug '15

You can use find(), buts its returning RESULTSET of OBJECTS(or ARRAYS/STDCLASSES if you selected any columns), you have to:

create seperate array $providersAccounts, and do foreach on $providers like this:

foreach($providers as $provider){ $providersAccounts[] = $provider->accounts->toArray(); }

and it should be working, also its good idea i think to store in associative array like this:

foreach($providers as $provider){ $providersAccounts+= [$provider->id => $provider->accounts->toArray()]; }

But i dot really know why you need it, i never needed in my life to select everything from manytomany relation.