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