Hey Sean, welcome to the forums. I think you need to restructure your database a bit. You need pivot tables (yes, that was the right term ;) ) only for many to many relationships.
That means if a company has many users (which is the case for your application) AND a user can have many companies (which I think is not intended) you need a pivot table. Otherwise a reference to the company_id in the users table is sufficient.
Furthermore can a single asset belong to a user AND a company? E.g. if a asset is assigned to a user it's automatically also assigned to a company. If not you might even get rid of asset_user and asset_company and use a polymorphic relation with asset as the morphable instead. See http://laravel.com/docs/eloquent#polymorphic-relations for further information.
If you think you're okay with your current database structure you could look into "Has Many Through"-Relationships (http://laravel.com/docs/eloquent#has-many-through). They seem to do what you're planning.
Regards Alex
Hi Alex. Thank you for the in depth reply and advice.
I guess I might be going about this the wrong way then. I just thought it would be easier having a companies_user table and an assets_company table for when I do lookups, so I wouldn't have to do any joins (I'm thinking less code).
I do need the asset_company table as an asset may belong to a company, but not to a user.
Thanks a lot, I'll take a look at redesigning my DB structure.
So,
Your db structure is like: "a user has many companies". But you ask: "give x of the company of a certain user".
So that's not possible cus a user has Many companies,
I suggest restructuring your db, but you could get all the assets of the First company of a user
$user = User::find( someid );
$user->companies()->first()->assets()->get(); // Or something like that
Or
$company = Company::whereHas('users', function($q) { $q->where('id', //someid//); })->with('assets')->first();
$assets = $company->assets;
// Many choices ! But i suggest you restructure your db & read the eloquent documents of laravel :)
LorenzV said:
So,
Your db structure is like: "a user has many companies". But you ask: "give x of the company of a certain user".
So that's not possible cus a user has Many companies,
I suggest restructuring your db, but you could get all the assets of the First company of a user
$user = User::find( someid );
$user->companies()->first()->assets()->get(); // Or something like that
Or
$company = Company::whereHas('users', function($q) { $q->where('id', //someid//); })->with('assets')->first();
$assets = $company->assets;
// Many choices ! But i suggest you restructure your db & read the eloquent documents of laravel :)
Thank you. I'll definitely give the docs a better read.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community