我有以下实体:
用户
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'members';
protected $primaryKey = 'member_id';
public function licences(){
return $this->hasMany('Licence', 'subid', 'member_id');
}
}
许可证
class Licence extends \Eloquent {
protected $table = 'licence';
protected $primaryKey = 'id';
protected $active = false;
const DATE_FORMAT = 'Y-m-d';
protected $fillable = [];
public function __construct(){
$this->checkifIsActive();
}
public function owner(){
return $this->belongsTo('User', 'member_id', 'subid');
}
public function checkifIsActive(){
if($this->start_date <= date($this->DATE_FORMAT) && $this->end_date >= date($this->DATE_FORMAT)) $this->active = true;
}
}
一个用户可以拥有许多许可证,用户拥有的许可证可以是活动的也可以是非活动的 - 这取决于许可证的开始和结束日期。
我试图加载用户对象,同时提取他们的许可证,但只提供那些活跃的许可证。
在许可证模型中,我正在设置“活跃的”#39;变量为true,当对象被实例化时,我们有办法知道许可证的状态。
我们尝试过的代码是:
return User::findOrFail($id)->with('licence.active')->get();
然而,这并不完全正确 - 因为没有对&licence.active&#39;进行实际情况检查。
我如何返回由ID加载的用户以及他们已关联的具有布尔值“活跃”的许可证。变量设置为&#39; true&#39;?
答案 0 :(得分:0)
您可以使用预先加载的约束来查询关系;
$user = User::with(array('license' => function($query){
$query->where('start', '<=', Carbon::now())
$query->where('end', '>=', Carbon::now())
}))->find($id);
这将只返回活动的许可证。
您可以选择查询关系的结果;
public function activeLicences(){
return $this->hasMany('Licence', 'subid', 'member_id')->where('start', '<=', Carbon::now())->where('end', '>=', Carbon::now());
}
然后你要做的就是得到以下结果;
$user = User::with('activeLicenses')->find($id)
请注意:尚未经过测试。