简体   繁体   中英

Laravel 4: Extend model's query to return additional fields with a model (no relations) but don't write data to attributes property

Suppose, I have some model-related data in several tables, other than the model resides it. Those tables are dynamically created (custom EAV implementation). How do I make Eloquent join those tables on queries it uses to fetch models without building a relation?

It would be good if I could hack into a query that Eloquent is going to use to return models from database after the query is fully constructed, but before it is executed.

Also, the problem is that data from joined tables should not go to model's attributes.

There is an easy way to add additional attributes in a model dynamically when querying the database using Eloquent and it won't be included with the model's attributes for example, if you want to add a field in the model which is not available in the model's attributes property but you want to use it like an attribute, then just create an accessor method in the model like this:

// In User model for example
public function getFullNameAttribute()
{
    return $this->first_name . ' ' . $this->last_name;
}

Now, if you use something like this:

echo User::find(1)->fullName;

Then you'll get a full name string (Concatenated first_name and last_name ) printed but actually there is no fullName field available as the model's attribute . This is called an accessor method and check the documentation for this ( Accessors & Mutators ) on Laravel website.

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