On my phone, but you can prefix the field with the table:
->where('categories.id','=',$category_id)
Tried that also, it returned me a "Column not found: 1054 Unknown column 'categories.id' in 'where clause' (SQL: select * from products
where active
= 1 and categories
.id
= 32 order by created_at
desc)"
If you come from the other direction this should work:
$products = Category::with(array('Product', function ($query) {
$query->where('active', true)->orderBy('created_at', 'desc');
}))->find($category_id)->Product();
Haven't tried it yet, but why would this work and not the other way around?
You should structure a query by selecting the smallest subset, which in this case is the category by ID, and then get the relation off that. The other way doesn't work because you were getting all products whether they had that category or not. You could definitely write a raw SQL query either way using joins, but this is the most straightforward way to do it with Eloquent.
I did it slightly different, because it would give me the error "explode() expects parameter 2 to be string, object given".
Changed this:
'Product', function($query) {
To this:
'Product' => function($query) {
Total:
$products = Category::with(array(
'Product' => function ($query) {
$query->where('active', '=', true)->orderBy('created_at', 'desc');
}
))->where('id', '=', $category_id)->get();
Though, with this code i get an other error which i don't quite understand why..
"Column not found: 1054 Unknown column 'products.category_id' in 'where clause' (SQL: select * from products
where products
.category_id
in (34) and active
= 1 order by created_at
desc)"
Yes, that was a typo. Sorry about that. What is the structure of the two tables?
Sorry for the late reply, these are the database structures i'm using:
Table: products
id
active
created_at
updated_at
(and more columns but they are not relevant)
Table: categories
id
created_at
updated_at
(and more inrelevant columns)
Table: join_category_product
id
category_id
product_id
Finally figured it out, had to use wherehas
In case someone is looking for a fix:
$products = Product::whereHas('Category', function ($query) use ($category_id) {
$query->where('categories.id', '=', $category_id);
})
->where('active', '=', true)
->orderBy('created_at', 'desc')
->get();
Hy,
I wonder if there is any way i don't have to type categories.id
into the where function?
When the name of the table categories
will change in the future I will have an error in this script...
Isn't this an error Eloquent should prevent us from?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community