我有两个相互连接的模型。
class Company extends Model {
public function addresses() {
return $this->belongsToMany('AppAddress', 'address_mapping', 'uid_company', 'uid_address');
}
}
class Address extends Model {
}
在我的 JOIN 表中,我有一个名为 active 的列。如何从公司获取所有活动地址?或者如何在 JOIN 表中实现 where 子句?
谢谢!
称为"JOIN 表"的表,通常称为数据透视表。您可以使用wherePivot
方法获取所有活动记录:
$company = Company::first();
$activeAdresses = $company->addresses()->wherePivot('active', 1);
或者,您可以直接在模型中定义关系:
class Company extends Model {
public function activeAddresses() {
return $this->belongsToMany('AppAddress', 'address_mapping', 'uid_company', 'uid_address')
->wherePivot('active', 1);
}
}
请参阅雄辩文档中通过中间表列过滤关系一节