【问题标题】:laravel - make a filter with relationslaravel - 用关系制作过滤器
【发布时间】:2019-01-19 20:50:52
【问题描述】:

我有一个包含关系的产品表: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"
          ]

我尝试做类似的事情,以便在过滤后从specValues 表中获取具有spespic 值的产品:

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

如何使用我的信息选择 where 选项?

【问题讨论】:

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


    【解决方案1】:

    你能试试这个代码吗?

    此代码用于关系,$specidsarr 是外部变量,用于关系中的条件,$q 正在处理所有外部条件。

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

    【讨论】:

    • 对不起,我没有成功,无法弄清楚如何将其更改为我的字段
    • 你可以试试用关系,with('specValues') 而不是 with(['specValues' => function($query) {$query->where("fld", "id");}])
    • 我在脸/书上给你发消息
    • 它没有用:/我是这样制作的:$products = $category->products()->with(['specValues' => function($query) { $query->where( 'specvalued_id','27535')->where("value", "2017"); }]);我得到了没有过滤器的计数:/
    • 只需更改查询内部,像这样,$query->where('specvalued_id','27535')->orwhere("value", "2017");
    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2020-09-08
    • 1970-01-01
    • 2016-10-15
    • 2021-08-07
    相关资源
    最近更新 更多