拉拉维尔:在关系中寻找


Laravel: search through relationships?

我不知道它是否真的可行,但它可能看起来像这样:

架构:

User
id, name, last_name, etc.
Condition
id, name
User_Condition
id, user_id, condition_id, active, start_date, end_date

我希望能够做类似的事情:$user->conditions->active()$user->conditions->active,其中它返回active=1

的任何行/关系

您想获得用户的所有活动条件,对吗?

如果是,您可以通过以下查询获得它们。

echo $user->conditions()->where('user_condition.active', true)->get();

确保在user model 中建立belongsToMany关系

public function conditions()
  {
      return $this->belongsToMany('App'Condition', 'user_condition');
  }

您正在寻找with过滤器,也称为Eager Load Constraints

$user->with['UserCondition'=>function($query){
                                 return $query->whereActive(1);
                             }
            ];

(假设在User雄辩模型中已经设置了UserCondition关系)。

来源:http://laravel.com/docs/5.0/eloquent