【问题标题】:Using Eloquent's hasMany relationship with whereIn使用 Eloquent 的 hasMany 关系与 whereIn
【发布时间】: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


【解决方案1】:

我相信一个合适的解决方案是使用 whereHas。您可以使用它进行更高级和更强大的查询。

https://laravel.com/docs/5.8/eloquent-relationships

use Illuminate\Database\Eloquent\Builder;

// Retrieve posts with at least one comment containing words like foo%...
$posts = App\Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

// Retrieve posts with at least ten comments containing words like foo%...
$posts = App\Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
}, '>=', 10)->get();

【讨论】:

    猜你喜欢
    • 2014-10-29
    • 2013-11-14
    • 2016-03-17
    • 2020-05-31
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2015-12-22
    • 2020-01-08
    相关资源
    最近更新 更多