【问题标题】:How to query relations in global scope in Laravel 4.2?如何在 Laravel 4.2 中查询全局范围内的关系?
【发布时间】:2014-07-28 12:47:12
【问题描述】:

我在 Laravel 中成功创建了一个全局作用域,我想在全局作用域中查询一个关系模型。我有一个视频模型、一个类别模式和一个 VideoCategory 枢轴模型,我想在全局范围内使用视频模型访问类别模型,例如:

<?php 
use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;

class DefaultScope implements ScopeInterface{

public function apply(Builder $builder)
{
    $model = $builder->getModel();

    $builder->whereHas('categories', function( $q ){
        $q->where('language', 2);
    });
}

public function remove(Builder $builder)
{

}
}

这有可能吗?

【问题讨论】:

    标签: php laravel frameworks


    【解决方案1】:

    简短回答:不要那样做

    怎么做?使用手动连接,但同样不要。

    它会导致错误、意外行为,一旦你开始工作,你就会退出它。

    Eloquent 在很多地方为模型创建了新的查询,使用has 是不可能的,我想你已经注意到了。使用手动连接可以让您对给定的模型执行此操作,但也会破坏 Eloquent 的 90% 基于关系的功能,即。你不能对这个模型使用haswith 等等。

    【讨论】:

    • 是的,你是对的。我已经使用了连接,结果非常令人满意。虽然我无法在全局范围内使用它,而是在模型范围内使用它,这也迫使我重写所有模型查询。我注意到使用 whereHas 和 Has 非常慢,所以我使用了 joins + scopes。有一件事是肯定的,我永远不会再使用 whereHas 和 Has。
    • 听起来很有趣。你怎么知道haswhereHas 很慢?比较到底是什么?
    • 与联接相比,whereHashas 的性能较慢。在我到达这个线程之前,我已经在 4.1 中体验过它。 [链接]github.com/laravel/framework/issues/3543
    猜你喜欢
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2019-03-29
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多