samedi 28 janvier 2017

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?

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:

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. With plain SQL, all I have to do is to add condition to JOIN, OR parameters.global = 1, like this:

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.

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.

Any help or advice is appreciated. Thank you.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kEZDxG
via IFTTT

Aucun commentaire:

Enregistrer un commentaire