【问题标题】:laravel 5- get related products by search in Many To Manylaravel 5-通过多对多搜索获取相关产品
【发布时间】:2018-10-29 20:05:16
【问题描述】:
Table 1: products: id,title
Table 2: features: id,name,values
Table 3:feature_product:id,product_id,values

当我在feature_product 表中搜索values 时,我想获得所有相关产品。

我做这些:

在产品型号中:

public function features()
{
    return $this->belongsToMany(Feature::class)->withPivot('values');
}

public function feature()
{
    // ???
}

和查询搜索:

 $q = 'yellow';
 $query->where(function($query) use ($q)
 {
    $query->WhereHas('feature' , function ($query) use 
    ($q){$query->where('values' , 'LIKE' , '%' . $q . '%' );});
 }

如何搜索产品的相关功能? (并获得这些产品)

我想我必须在产品模型的这个功能中做一些事情:

public function feature()
{
        // ???
}

【问题讨论】:

  • 您必须在两个模型中定义belongsToMany() 关系。两者都一样,只需更改其中的模型名称即可。
  • 你的问题解决了吗?
  • @NaveedAli 是的,有这个:$query->WhereHas('features' , function ($query) use ($q){$query->where('feature_product.values' , 'LIKE' , '%' . $q . '%' );});。你的评论对我有帮助。

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


【解决方案1】:

在产品型号中:

public function features()
{
  return $this->belongsToMany(Feature::class)->withPivot('values');
}

public function feature()
{
   // ??
}

在特征模型中:

public function products(){
 return $this->belongsToMany('App\Product')->withPivot('values');
}

查询搜索

$query->WhereHas('features' , function ($query) use ($q) {
$query->where('feature_product.values' , 'LIKE' , '%' . $q . '%' );
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-06
    • 2013-09-30
    • 2015-10-29
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2019-07-08
    相关资源
    最近更新 更多