I suspect that a lot of what you're interested in doing can be accomplished through eloquent's support for relationships. For example, you could describe a user's favorite companies using a many-to-many relationship, like so:
class User
{
public function favoriteCompanies()
{
//"Company" is the eloquent model you're linking to
//"user_company_favorites" is the pivot table with columns for the user_id and a company_id
return $this->belongsToMany('Company', 'user_company_favorites');
}
}
class Company
{
public function favoriteOf()
{
return $this->belongsToMany('User', 'user_company_favorites');
}
}
Now, assuming you have this in your "user_company_favorites" table:
id | user_id | company_id
1 | 7 | 4
2 | 7 | 12
3 | 4 | 4
4 | 5 | 16
5 | 4 | 16
$someUser = User::find(7);
$someUser->favoriteCompanies; //collection containing companies with the IDs 4 and 12
$someCompany = Company::find(16);
$someCompany->favoriteOf //collection containing users with the IDs 4 and 5
More on relationships: http://laravel.com/docs/eloquent#relationships
You can also use a super-handy feature called query scopes to do similar things. For example:
class Company
{
function scopeInCounty($query, $countryCode)
{
$query->where('country_code', $countryCode);
}
}
Now, you can use that function in your queries:
$activeCompaniesInUs = Company::where('status', 1)->inCountry('US')->get();
The above code is identical to:
$activeCompaniesInUs = Company::where('status', 1)->where('country_code', 'US')->get();
More on query scopes: http://laravel.com/docs/eloquent#query-scopes
Those two features should alleviate 99% of your need to use the DB facade inside your model class. But if not, there's no reason why you can'd do that as well.
Thank you very much.
I knew Eloquent had some relationship features, but I wasn't sure what the performance implications might be. I'm also managing my learning curve and was looking to just write custom methods and SQL for specific data structures I'm interested in because it's familiar.
But the demo you gave (belongsToMany) looks good.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community