【问题标题】:Refactor merged query in Laravel在 Laravel 中重构合并查询
【发布时间】:2021-05-04 16:24:29
【问题描述】:

我目前有 2 种方法可以双向执行搜索查询,然后将它们合并在一起以检索结果。

模型关系

public function linkedTo() {
    return $this->hasMany(Linked::class, 'team_id');
}

public function linkedFrom() {
    return $this->hasMany(Linked::class, 'linked_id');
}

查询

$linkedTo = $team->linkedTo()->with(['games' => function ($query) use ($search) {
    $query->where('title', 'like', "%$search%");
}])->get();

$linkedFrom = $team->linkedFrom()->with(['games' => function ($query) use ($search) {
    $query->where('title', 'like', "%$search%");
}])->get();

$links = $linkedTo->merge($linkedFrom);

为了从搜索结果中获得我需要的结果,我必须将它们合并在一起。

有没有一种更简洁的方法可以在一个查询中将它们连接在一起?

【问题讨论】:

  • with 中使用的函数分配给变量会更简洁,例如$callback = function ($query) use ($search) ... 并在两个查询中重复使用它。除此之外,可能还有更多事情要做,但它们实际上取决于您的数据结构以及您实际尝试检索的内容。
  • @apokryfos 你有这方面的例子吗?格式问题

标签: mysql laravel eloquent


【解决方案1】:

如果您想减少代码重复(但实际上不改变执行的内容),您可以这样做:

$filter = function ($query) use ($search) {
    $query->where('title', 'like', "%$search%");
};
$linkedTo = $team->linkedTo()->with(['games' => $filter ])->get();
$linkedFrom = $team->linkedFrom()->with(['games' => $filter ])->get();
$links = $linkedTo->merge($linkedFrom);

【讨论】:

  • 是的,在不改变输出的情况下减少了我的方法。谢谢
【解决方案2】:

使用union:

// First build the queries, note I removed 'get()'
$linkedTo = $team->linkedTo()->with(['games' => function ($query) use ($search) {
    $query->where('title', 'like', "%$search%");
}]);

$linkedFrom = $team->linkedFrom()->with(['games' => function ($query) use ($search) {
    $query->where('title', 'like', "%$search%");
}]);

// Now union and get the results
$links = $linkedTo->union($linkedFrom)->get();

更多详情:https://laravel.com/docs/8.x/queries#unions

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 2018-04-22
    • 2020-07-18
    • 1970-01-01
    • 2019-10-17
    • 2016-03-30
    • 2016-12-15
    • 2021-12-26
    相关资源
    最近更新 更多