I'm having trouble using $appends when retrieving a relationship using eager $with. Now this is just a simple example I put together.
User.php
class User extends Eloquent {
protected $with = array('account');
public function account() { return $this->hasOne('Account'); }
}
Account.php
class Account extends Eloquent {
protected $hidden = array('pin');
public function user() { return $this->hasOne('User'); }
public function getPinAttribute() {
return $this->attributes['pin']; // or a computed value
}
}
Now using the ->setAppends() I should be able selectively include it in the results of ->toArray(). For instance:
$account = Account::find(1);
$account->setAppends(array('pin'));
$account->toJSON();
/* results includes the pin */
However, this doesn't seem to work through a relationship / eager loading.
$user = User::find(1);
$user->setAppends(array('pin'));
/* or $user->account->setAppends(array('pin')); */
$user->toJSON();
/* results does not include pin, append doesn't effect result. */
Is there a way to set an $appends through an eager load or relationship?
Sources: http://laravel.com/docs/eloquent#converting-to-arrays-or-json
I would expect the responding array to contain the Appends attribute. In this case the pin.
For instance the the setAppends works as follows:
$account = Account::find(1);
$account->setAppends(array('pin'));
$account->toJSON();
And it's result something like (includes pin because of setAppends):
{
"name": "Account1",
"type": "blue",
"pin": 1234
}
Now the append through a relationship (or eager load) ideally would be able to also use setAppends:
$user = User::find(1);
$user->setAppends(array('pin'));
/* or $user->account->setAppends(array('pin')); */
$user->toJSON();
And it's expected result something like:
{
"first_name": "Bob",
"last_name": "Hope",
"account": {
"name": "Account1",
"type": "blue",
"pin": 1234
}
}
However the 'pin' doesn't get included as expected as hoped.
At the time of this writing the only way of doing what you want is manually.
$account = Account::find(1);
$account->pin = $account->pin;
$account->toJSON();
Since then I made a commit to the framework adding the append()
method.
Now you use it like this:
$account = Account::find(1)->append('pin')->toJSON();
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community