如何从laravel中的多个与多个关系中获取活动元素

时间:2018-05-15 14:21:00

标签: php laravel eloquent

我遇到了多对多关系和条款翻译的问题。 我有4张桌子:

products
    - id, price, whatever
products_lang
    - id, product_id, lang, product_name
accessori
    - id, active
accessori_lang
    - id, accessori_id, lang, accessori_name

我正在尝试将配件分配给名为:

的中间表的产品
accessori_products

这是产品的模型:

class Product extends Model {

    protected $table = 'products';

    public function productsLang () {
        return $this->hasMany('App\ProductLng', 'products_id')->where('lang','=',App::getLocale());
    }

    public function productsLangAll() {
        return $this->hasMany('App\ProductLng', 'products_id');
    }

    public function accessori() {
        return $this->belongsToMany('App\Accessori', 'accessori_products');
    }
}

这是productLng的模型:

class ProductLng extends Model {

    protected $table = 'products_lng';

    public function products() {
        return $this->belongsTo('App\Product', 'products_id', 'id');
    }
}

然后我有了Accessori的模型:

class Accessori extends Model {

    protected $table = 'accessori';

    public function accessoriLang() {
        return $this->hasMany('App\AccessoriLng')->where('lang','=',App::getLocale());
    }

    public function accessoriLangAll() {
        return $this->hasMany('App\AccessoriLng');
    }

    public function accessoriProducts() {
        return $this->belongsToMany('App\Products', 'accessori_products', 'accessori_id', 'products_id');
    }
}

AccessoriLng的模型:

class accessoriLng extends Model {

    protected $table = 'accessori_lng';

    public function accessori() {
        return $this->belongsTo('App\Accessori', 'accessori_id', 'id');
    }
}

我得到的结果是:

$products = Product::has('accessori')->with([
  'productsLang ',
  'accessori' => function ($accessori){
      $accessori->with([
        'accessoriLang'
      ]);
   }
])->get();

return $products;

但是我想只获得像where accessori.active = 1这样的活动配件,但我真的不知道放在哪里。我尝试过不同的方式但是我坚持了2天。

1 个答案:

答案 0 :(得分:1)

IIRC你不需要多对多关系中的中间表模型。

如果您想要返回Accessori处于活动状态的产品,您可以在产品型号上使用whereHas

$prod = Product::whereHas('accessori', function($query) {
  $query->where('active', 1);
})->get();

$query param将在Accessori模型上运行。

您也可以使用Accessori to Product进行反向操作。

$acessoris = Accessori::where('active', 1)->whereHas('accessoriProduct')->with(['accessoriLang', 'accessoriProducts.productsLang'])->get();