I am new to laravel.
I need to join two tables, and i dont know what i am doing wrong.
When i check at telescope, my query isnt displayed.
This is the query i want to run
SELECT * FROM products join subcategories on products.subcategories_id = subcategories.id where subcategories.categories_id = 1
In my laravel controller i have
public function showCategoriesProducts(String $cat){
$categories = Categories::all();
$products = Products::join('subcategories', function($join) {
$join->on('products.subcategories_id', '=', 'subcategories.id');
}) ;
dd($products);
return view('products.index',compact('products','categories'));
}
This is my web.php
Route::get('/categories/{categories_id}', 'ProductController#showCategoriesProducts')->name('categories.show');
My Products belong to subcategories and subcategories belong to Categories. I need to fetch products from category id.
Please Help
Thank You!
You are building the query, but not fetching records. Add ->get() add the end of your query to make the request.
$products = Products::join('subcategories', function($join) {
$join->on('products.subcategories_id', '=', 'subcategories.id');
})->get();
Related
I have 3 tables i.e category, sub category and products. I have passed category id to sub category and then sub category id to product so that i can get the whole data as per requirements. The problem in i an able to get the data from the secondary tables that has joins statement not from the primary table.Here is my code of query. Any help from you would be appreciated
public function showProduct()
{
$data = DB::table('category')
->join('sub_category','category.id',"=",'sub_category.category_id')
->join('product','sub_category.id', '=', 'product.sub_category_id')
->get();
return $this->success('date' ,$data);
}
use leftjoin
$data = DB::table('category')
->leftjoin('sub_category','category.id',"=",'sub_category.category_id')
->leftjoin('product','sub_category.id', '=', 'product.sub_category_id')
->get();
I have two tables (Table1, Table2).
I want to print the sum of the records whose properties match Table1 in Table2 while listing the Table1 table.
My two tables contain very large records, performance is important to me.
// Model -> relationships
public function cars()
{
return $this->hasMany('App\Models\Table2', 'list_id', 'list_id');
}
// Controller
$table1 = Table1::with('cars' => function($query){
$query->where('table2.color','=', 'table1.color')
$query->where('table2.year','=', 'table1.year')
}])
->get();
I'm adding the sample database pictures:
Thank you.
First, add below use statement to the top of your controller:
use DB;
Now, If you only want to get the records amount, you can do this:
$amount = DB::table('table1')
->join('table2', function($join){
$join->on('table1.color', '=', 'table2.color');
$join->on('table1.year', '=', 'table2.year');
})->count();
But if you want to get the list of the table1 records, you can change the query a bit like below:
$records = DB::table('table1')
->select('table1.*')
->join('table2', function($join){
$join->on('table1.color', '=', 'table2.color');
$join->on('table1.year', '=', 'table2.year');
})->count();
Please follow Laravel's official guide on this topic:
https://laravel.com/docs/8.x/queries#advanced-join-clauses
Use join to merge the two tables read more about join here https://www.w3schools.com/sql/sql_join.asp
In laravel 8, I am filtering blog articles by category. However when I select multiple categories in my select menu. I do get the proper request . for example: articles/category/?category_ids=3,4
But it will only output one selected filter. If I select 2 filters it just selects that next filter as if I only selected that one. (I also use Axios but the request is done proper, so its in my Controller)
Here is my code I tried:
$data['articles'] = Article::whereHas('categories', function ($query) use($category_ids){
$query->whereHas('category_id', '=', $category_ids)->where('premium',0);
;})->get();
I also tried:
$data['articles'] = Article::whereHas('categories', function ($query) use($category_ids){
$query->whereIn('category_id', [$category_ids])->where('premium',0);
;})->get();
So how do I get to query both or more category id's ?
I am using a pivot table:
Articles can have many Categories
Categories can have many Articles
I use article_category as a pivot table
When checking for relationship existence in many-to-many relations, the check is still to be done against the id in the categories table.
Try this
$category_ids = collect(explode(',', $request->category_ids))
->map(fn($i) => trim($i))
->all();
$data['articles'] => Article::whereHas('category', fn($query) =>
$query->whereIn('categories.id', $category_ids)
->where('categories.premium', 0)
)->get();
You can explode the categories and then make the query like this.
$categories = explode(',',$request->categories);
$data['articles'] = Article::whereHas('categories', function ($query) use($categories){
$query->whereIn('category_id', $categories)->where('premium',0);
})->get();
I have Invoice_Detail model which handles all products and it's quantities, this model table invoice_details has item_id and qty columns.
The Invoice_Detail has a relation to Items model which holds all item's data there in its items table, which has item_id, name, category_id.
The Item model also has a relation to Category model which has all categories data in its categories table.
Question: I want to select top five categories from Invoice_Detail, how?
Here's what I did:
$topCategories = InvoiceDetail::selectRaw('SUM(qty) as qty')
->with(['item.category' => function($query){
$query->groupBy('id');
}])
->orderBy('qty', 'DESC')
->take(5)->get();
But didn't work !!
[{"qty":"11043","item":null}]
Category::select('categories.*',\DB::raw('sum("invoice_details"."qty") as "qty"'))
->leftJoin('items', 'items.category_id', '=', 'categories.id')
->leftJoin('invoice_details', 'invoice_details.item_id', '=', 'items.id')
->groupBy('categories.id')
->orderBy('qty','DESC')
->limit(5)
->get();
This will return you collection of top categories.
Tested on laravel 5.5 and PostgreSQL.
UPD:
To solve this without joins you can add to Categories model this:
public function invoiceDetails()
{
return $this->hasManyThrough(Invoice_Detail::class, Item::class);
}
And to select top 5 categories:
$top = Category::select()->with('invoiceDetails')
->get()->sortByDesc(function($item){
$item->invoiceDetails->sum('qty');
})->top(5);
But first solution with joins will work faster.
I have model many-to-many (including pivot table). I need to pull out only the products that belongs to a certain category. I'm trying this but it gives me all the products:
$products = User::whereHas('category', function ($query) {
$query->where('id','1');
})->get();
1 in where is just for testing because when I put $id that was defined outside query it doesn't recognize it.
Try this.
$products= User::whereHas('category', function ($query) use ($id) {
$query->where('id', $id);
})->get();
Maybe the fetchProducts method here will shed some light: Getting product brands, their categories and associated products