【发布时间】:2017-06-03 18:25:54
【问题描述】:
我有点卡在这里,不知道如何继续前进。
我有两个模型:user 和 child,他们处于Relationship中。
(请记住,这只是说明问题)
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\Child','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;
}
}
现在我想在控制器中使用 Eager Loading 从用户那里检索我的 Childs 数据。
但我的用户模型对象来自我的应用程序中的中间件。所以我只有用户模型对象可以使用,我不想再次使用“with()”查询用户。
$user = User::where('name','DoctorWho')->first();
return user->childs()->find(3);
此操作返回的内容:
{
"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
}
我需要什么(附加属性)
{
"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
}
甚至可以使用 Eager Loading 检索具有 附加属性 的子数据吗?
注意:这个用户对象来自一个中间件,我必须使用用户模型对象来获取它的子对象,并附加属性。
提前致谢, 洛斯罗伯斯
【问题讨论】:
标签: laravel laravel-5 eloquent