samedi 3 juin 2017

Eloquent Eager Loading with $append Attribute

I'm kinda stuck with this here and don't know how to move forward with this one.

I have two Models: user and child and they are in a Relationship.

( Keep in mind that this only illustrate the problem )

class Child extends Model{

    protected $primaryKey = 'id_child';

    public $appends = ['is_alive'];

    public function user(){

        return $this->belongsTo('Models\User','id_user');

    }

    public function getIsAliveAttribute(){

        if (!is_null($this->lifetime_updated_at))
            return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
        else
            return false;
    }
}

class User extends Model{

    protected $primaryKey = 'id_user';

    public $appends = ['is_alive'];

    public function childs(){

        return $this->hasMany('Models\User','id_user');
}

public function getIsAliveAttribute(){

    if (!is_null($this->lifetime_updated_at))
        return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
    else
        return false;
}

}

Now I want to use Eager Loading in the Controller to retrieve my Childs data from User.

$user = User::where('name','DoctorWho')->first();

return user->childs()->find(3);

What this operation returns:

    {
        "id_child": 3,
        "name": "JayZ",
        "last_name": "Etc",
        "lifetime": 1,
        "lifetime_updated_at": null,
        "created_at": "2017-05-29 21:40:02",
        "updated_at": "2017-05-29 21:40:02",
        "active": 1   
}

What I needed ( With Attribute Appended)

{
    "id_child": 3,
    "name": "JayZ",
    "last_name": "Etc",
    "lifetime": 1,
    "lifetime_updated_at": null,
    "created_at": "2017-05-29 21:40:02",
    "updated_at": "2017-05-29 21:40:02",
    "active": 1,
    "is_alive": true
  }

Is even possible to retrieve Child Data with Appended Attributes using Eager Loading ?

Thanks in Advance, LosLobos



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2qLG9ql
via IFTTT

Aucun commentaire:

Enregistrer un commentaire