laravel-使用关系过滤

时间:2018-08-13 07:15:23

标签: laravel eloquent laravel-query-builder laravel-filters

我有一个具有以下关系的产品表:specValues

在我的产品模型中:

public function specValues(){
    return $this->morphMany('App\Models\SpecValue', 'specvalued');
}

在我的specValues中有:

class SpecValue extends Model
{
  use Cachable;

    protected $table = 'specvalued';
    protected $fillable = ['field_id', 'value', 'value_desc', 'link', 
                           'specvalued_id', 'specvalued_type'];
    public $timestamps = false;

    public function specvalued()
    {
        return $this->morphTo();
    }

    public function field()
    {
        return $this->belongsTo('App\Models\SpecField','field_id');
    }
}

现在,我想为产品列表制作一个过滤器和一个多功能过滤器: 与specvalued()(来自specvalued表)一起获得名称(或ID) 并带有specvalued表中的“值”字段。

带有产品的specValues看起来像这样:(我很喜欢,但是具有不同的specvalued_idvalue,我想为此创建一个过滤器。

#attributes: array:8 [▼
            "id" => 354327
            "field_id" => 4
            "specvalued_id" => 27535 //(name = year)
            "specvalued_type" => "Model\Product"
            "value" => "2017"
            "value_desc" => null
            "link" => null
            "created_at" => "2017-09-03 10:12:30"
          ]

然后我尝试进行类似的操作,以在过滤器之后从spespic表中获得具有specValues值的产品:

$products = $category->products()->with('specValues')->
where ????
orderBy('position')->paginate(20);

我该如何查看我的信息?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此代码吗?

此代码与关系一起使用,$specidsarr是与条件一起使用的外部变量,并且$q在所有外部条件下都可以使用。

$products = $category->products()->with(['specValues' => 
    function($q) use($specidsarr) {
        $q->whereIn('feild', $specidsarr);
    }
]);
相关问题