简体   繁体   English

Laravel ManyToMany加入条件

[英]Laravel ManyToMany Join On Condition

Greetings to everyone. 致大家。

How can I add condition to "join on" for belongsToMany (many to many) relation in Laravel 5.3? 如何在Laravel 5.3中为beforeToMany(多对多)关系在“ join on”上添加条件?

For example, let's say here are Products and Parameters of those Products with many to many relation. 例如,假设这里是具有多对多关系的产品和这些产品的参数。 When I want to get all Parameters for specific Product, it is just fine. 当我想获取特定产品的所有参数时,就很好了。 I do $product->parameters and it gives me what I need with query like this: 我做$product->parameters ,它给了我查询所需的东西:

SELECT
  parameters.*,
  product_parameters.product_id AS pivot_product_id,
  product_parameters.parameter_id AS pivot_parameter_id
FROM parameters
  INNER JOIN product_parameters ON parameters.id = product_parameters.parameter_id
WHERE product_parameters.product_id = 1;

Problem appears when I want to define some "Global" flag on Parameter which defines that Parameter should be bound to every Product. 当我想在Parameter上定义一些“全局”标志时出现问题,该标志定义该Parameter应该绑定到每个产品。 With plain SQL, all I have to do is to add condition to JOIN, OR parameters.global = 1 , like this: 使用普通SQL,我要做的就是将条件添加到JOIN 或parameters.global = 1中 ,如下所示:

SELECT
  parameters.*,
  product_parameters.product_id AS pivot_product_id,
  product_parameters.parameter_id AS pivot_parameter_id
FROM parameters
  INNER JOIN product_parameters ON parameters.id = product_parameters.parameter_id OR parameters.global = 1
WHERE product_parameters.product_id = 1;

But I didn't find if there is correct and clean way to do it with Laravel to be able to get Eloquent\\Relation object back from function with additional data I require. 但是我没有发现是否有正确和干净的方法可以用Laravel做到这一点,以使Eloquent \\ Relation对象能够从函数中获得我需要的其他数据。

I have found "bad" way, which is to "fetch" join which I need from query builder object and add another "where" to it, but it is very ugly and I'm not sure that it will work in future without problems. 我发现了一种“糟糕”的方式,即从查询生成器对象中“获取”所需的联接并向其添加另一个“位置”,但是这种方式非常难看,我不确定它将来是否会正常工作。

This is what I have tried to do and it almost worked (have problem with incorrect number of PDO parameters, but it generates SQL which I need): 这是我尝试执行的操作,几乎可以正常工作(PDO参数数量不正确,但它会生成我需要的SQL):

$relation = $this->belongsToMany(Parameter::class, 'product_parameters');
$relation->getQuery()->getQuery()->joins[0]->where('parameters.definition', '=', 0, 'or');

Any help or advice is appreciated. 任何帮助或建议,不胜感激。 Thank you. 谢谢。

I have left original idea to place everything in queries, tried to do several requests and combine resulting Eloquent Collections. 我留下了最初的想法,将所有内容放入查询中,尝试执行多个请求并合并生成的Eloquent Collections。 Then I did some research and in the end I decided that what I was going wrong way, and it is better to use patterns like Repository and Specification to achieve required logic. 然后我做了一些研究,最后我确定了我要走错的路,最好使用存储库和规范之类的模式来实现所需的逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM