Laravel Scope 通过数据透视值

标签 laravel laravel-4

假设我想存储有关客户的各种数据,所以我有两个由数据透视表链接的模型,在数据透视表上存储每个数据字段类型的客户值:

Customer {
    public function datafields()
    {
        return $this->belongsToMany('Datafield')->withPivot('value');
    }
}


Datafield {
    public function customers()
    {
        return $this->belongsToMany('Customer')->withPivot('value');
    }

所以我的表是customers、customer_datafield、datafields。

如何在客户中设置查询范围以查找特定数据字段的值为 x 的所有客户?

类似的东西
Customer {
    public function datafields()
    {
        return $this->belongsToMany('Datafield')->withPivot('value');
    }
    public function scopeSearch($query, $searchfor)
    {
        return $query->datafields()->pivot()
            ->where('value', $searchfor)
            ->where('datafield_id', 123);
    }
}

我尝试了几种方法,但没有任何运气让一种方法起作用。任何建议非常感谢!

最佳答案

单个固定枢轴字段的 Eloquent 方式:

public function scopeDataValue($query, $search)
{
    $pivot = $this->datafields()->getTable();

    $query->whereHas('datafields', function ($q) use ($search, $pivot) {
        $q->where("{$pivot}.value", $search);
    });
}

// usage
Model::

这为您提供了更多的功能和灵活性:
public function scopeDataValues($query, array $search, $bool = 'and')
{
    $pivot = $this->datafields()->getTable();

    $query->whereHas('categories', function ($q) use ($search, $pivot, $bool) {
        $q->where(function ($q) use ($search, $pivot, $bool) {
            foreach ($search as $field => $value)
            {
                $q->where("{$pivot}.{$field}", '=', $value, $bool);
            }
        });
    });
}

// usage
Model::dataValues(['value' => 'findMe', 'otherField' => 'findMeToo'])->get();

Model::dataValues(['value' => 'findMe', 'otherField' => 'orFindMe'], 'or')->get();

您可能会想使用 where用数组代替 foreach在第二个闭包中,但是它可能无法按预期工作,因为字段不会以表名为前缀。

另一种解决方案是使用简单的 join :
public function scopeDataValue($query, $search)
{
    $pivot = $this->datafields()->getTable();

    // first get array of already joined table
    $base = $query->getQuery();
    $joins = array_fetch((array) $base->joins, 'table');

    $foreignKey = $this->categories()->getForeignKey();

    // if table has not been joined, let's do it
    if ( ! in_array($pivot, $joins))
    {
        $query->join($pivot, $this->getQualifiedKeyName(), '=', $foreignKey);
    }

    $query->where("{$pivot}.correct", $search);
}

// usage
Model::dataValue(2)->take(..)->where(..)->dataValue(5)->get();

您可以按照与上面的第二个示例相同的方式对其进行更改。

关于Laravel Scope 通过数据透视值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26073924/

相关文章:

php - 在 laravel 5 的子文件夹下创建 Controller 的正确方法

php - 如何在 Laravel 中发生异常后继续执行?

php - PHP中maximum_execution_time的最大值是多少?

laravel - Laravel 8 的动态路线

laravel - Laravel 数据迁移的推荐/标准处理

php - Laravel 链接到路由未定义

php - laravel blade,如何附加到一个部分

apache - 在 laravel @Apache2 Server Ubuntu 14.04 LTS 中将根设置为公共(public)文件夹

php - Laravel 4 加密 : how many characters to expect

php - Laravel 5.3 密码代理自定义