M
M
muhasa2019-08-01 14:27:35
Laravel
muhasa, 2019-08-01 14:27:35

How to query all values ​​of some attribute in Eloquent that has a many-to-many relationship?

Hello.
There was such a task - there is a table of goods (products) , there is a table of attributes ( attributes ), there is a connecting (pivot) table, where product_id, attribute_id and some value at the intersection (value).
How do I pull out all values ​​for an attribute under id = 1, 2, etc.?
That is, the first attribute, for example, product type . In his pivot table, in the value value , there can be anything for each individual product. I want to see generally all values ​​for attribute_id = 1 (product type).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2019-08-01
@muhasa

DB::table('pivot_table')->where('attribute_id',1)->pluck('value');

G
Grigory Vasilkov, 2019-08-01
@gzhegow

Try this:
Products.php
public function attributes()
{
return $this->hasManyThrough(Attributes::class, ProductsAttributes::class...); // here you need to google the correct order of the keys, I don't remember
}
$product = Products::first(); // get the product
$query = $product->attributes(); // create query SELECT FROM attributes WHERE exists({subquery});
$query->select('value')->where('id', 1)->get(); // all value values ​​bound to the first product for attribute 1 (but here it's some kind of game, usually one attribute per product, but you get a product type that can contain attribute 1 several times?)
If you need all values ​​for all products, then straightaway
Attributes::where('id', 1)->select('value')->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question