简体   繁体   中英

Laravel Eloquent Model Unbindings

I have recently started using Laravel and I would like to know if there is a way to unbind model relationships in specific calls. For example if one of my models got a hasOne binding, I have a particular call that I don't want that relationship to be retrieved to eliminate extra database calls. I know that this is possible in CakePHP but haven't found a way to do it in Laravel yet.

Thanks

Relationships in Laravel are only eager loaded if specified. If you don't eager load the relationship, it will be lazy loaded the first time you try to access it, making it appear as if it had already be loaded.

User class:

class User extends Eloquent
{
    public function userTransactions()
    {
        return $this->hasMany('UserTransaction');
    }
}

Eager loading:

// runs one query to get the user, and a second query to get the user
// transactions for the user
$user = User::with('userTransactions')->find(1);

Lazy loading:

// runs one query to get the user
$user = User::find(1);

// first time the userTransactions property is accessed, it runs the query
// to get the user transactions for the user.
print_r($user->userTransactions->lists('id'));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM