http://laravel.com/docs/4.2/eloquent#dynamic-properties
class Phone extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
$phone = Phone::find(1);
Now, if I then do something like this:
echo $phone->user->email;
echo $phone->user->name;
echo $phone->user->nickname;
Will Eloquent make a database call for every time I use the ->user
dynamic property? Or is this smart enough to cache the user on the first call?
Based on this, is it correct to say that the 'dynamic property' is a one-time call to the database when the property value is first called and it loads a collection. That collection can then be operated upon with the various methods like first() but the underlying data will not change.
Laravel Eloquent, in short, helps to do a simplified synchronization of the multiple databases which are running on many different systems. Your primary responsibility is just to define database tables and the relations which exist between them.
The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Before getting started, be sure to configure a database connection in config/database. php .
A scope is a method in your model that makes it able to add database logic into your model. Scopes make it able to reuse query logic by allowing to encapsulate database logic into a model.
In your example, the user
attribute on the $phone
object will be lazy loaded, but it will only be loaded once.
Keep in mind, as well, that once the object is loaded, it does not reflect any changes to the underlying table unless you manually reload the relationship using the load
method.
The following code illustrates the example:
$phone = Phone::find(1);
// first use of user attribute triggers lazy load
echo $phone->user->email;
// get that user outta here.
User::destroy($phone->user->id);
// echoes the name just fine, even though the record doesn't exist anymore
echo $phone->user->name;
// manually reload the relationship
$phone->load('user');
// now will show null, since the user was deleted and the relationship was reloaded
var_export($phone->user);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With