【发布时间】:2019-11-12 14:50:56
【问题描述】:
我有一个带有标识符数组的用户模型。标识符可以是 IP 地址或其他东西。用户可以被禁止,这是通过他们的标识符来完成的。但是,我似乎无法使用 Eloquent 的 HasMany 关系来完成这样的逻辑。
我想要这样,只要有一个 Ban 模型(条目),其中标识符与用户的标识符数组中的标识符之一匹配,那么它应该被添加到该 hasMany 关系中。
我尝试将“HasMany”与“whereIn”一起使用,但这不起作用,因为它仍会查找外键关系,然后应用“whereIn”约束。这不是我想要的。
这是我尝试定义用户与禁令的关系的方式。
public function bans()
{
// Due to how banning works, there might exist a ban record for
// each of the player's identifier (steam, IP address
// rockstar license, etc.), and it's essential to get all.
// All ban records where the identifier column equals one of
// the user's identifiers (array)
return $this->hasMany(Ban::class)->whereIn('identifier', $this->identifiers);
}
预期的是它应该返回在其标识符列中具有用户标识符之一的所有禁止记录。但这不起作用,因为 HasMany 仍然应用外键相等检查。
提前致谢!
【问题讨论】:
-
简而言之,没有内置的方法可以做到这一点。如果您真的无法添加外键(例如
user_id),您唯一的选择是从头开始编写自定义关系或使用诸如github.com/johnnyfreeman/laravel-custom-relation 之类的特征。请注意,作者提到它尚未准备好生产
标签: php laravel laravel-5 eloquent