Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

mike-healy mike-healy Joined 11 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.