Laravel: 搜索关系?

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() or $user->conditions->active where it returns any row/relations in which active = 1

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

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

(假设UserCondition关系已经在Usereloquent模型中设置。

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

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

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

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

确保在 user model

中建立 belongsToMany 关系
public function conditions()
  {
      return $this->belongsToMany('App\Condition', 'user_condition');
  }