Self Join in laravel - php

I have read some same question but i don't get any solution. I have one table name "Category". I have three column id, parent_id, name. I want to display records with parent_id name.
Right now records are displaying like....
id parent_id name
1 0 Mobile
2 0 TV
3 1 Samsung
But I want...
id parent_id name
1 0 Mobile
2 0 TV
3 Mobile Samsung
I tried this but it display error Syntax error or access violation: 1066 Not unique table/alias: 'category'
DB::table('category')->join('category','category.id','=','category.parent_id')->where('category.parent_id','>',0)->get();
I have solved my proble by this query.....
$sql = "select category1.name as name1, category2.name as name2, category1.id,category1.parent_id";
$sql .= " from category as category1 left join category as category2 on category1.id=category2.parent_id where category2.parent_id >0";
return DB::select($sql);

Try following query
$result = DB::table('category as c1')
->leftJoin('category as c2','c1.id', '=', 'c2.parent_id')
->where('c1.parent_id','>',0)->get();

Try Below Query
$result = DB::table('category as c1')
->join('category as c2','c1.id', '=', 'c2.parent_id')
select(
'id',
'name',
DB::raw('( case when c1.parent_id > 0 then c2.name ELSE c1.parent_id End ) as "parent_id"'),
->get();

Related

Multiple leftJoins using Laravel's Query Builder producing incorrect counts

I am using Laravel 5.4's Query Builder to perform a series of leftJoins on three tables. Here are my tables:
items
id type title visibility status created_at
-- ---- ----- ---------- ------ ----------
1 1 This is a Title 1 1 2017-06-20 06:39:20
2 1 Here's Another Item 1 1 2017-06-24 18:12:13
3 1 A Third Item 1 1 2017-06-26 10:10:34
count_loves
id items_id user_id
-- ------- -------
1 1 2
2 1 57
3 1 18
count_downloads
id items_id user_id
-- ------- -------
1 1 879
2 1 323
And here is the code I am running in Laravel:
$items_output = DB::table('items')
->leftJoin('count_loves', 'items.id', '=', 'count_loves.items_id')
->leftJoin('count_downloads', 'items.id', '=', 'count_downloads.items_id')
->where('items.visibility', '=', '1')
->where('items.status', '=', '1')
->orderBy('items.created_at', 'desc')
->select('items.*', DB::raw('count(count_loves.id) as loveCount'), DB::raw('count(count_downloads.id) as downloadCount'))
->groupBy('items.id')
->get();
When I return the results for this query, I am getting the following counts:
count_loves: 6
count_downloads: 6
As you can see, the actual count values should be:
count_loves: 3
count_downloads: 2
If I add another entry to the count_loves table, as an example, the totals move to 8. If I add another entry to the count_downloads table after that, the totals jump to 12. So, the two counts are multiplying together.
If I die and dump the query, here's what I get:
"query" => "select 'items'.*, count(count_loves.id) as loveCount,
count(count_downloads.id) as downloadCount from 'items' left join
'count_loves' on 'items'.'id' = 'count_loves'.'items_id' left join
'count_downloads' on 'items'.'id' = 'count_downloads'.'items_id'
where 'items'.'visibility' = ? and 'items'.'status' = ? group by
'items'.'id' order by 'items'.'created_at' desc"
How do I perform multiple leftJoins using Query Builder and count on several tables to return the proper sums?
NOTE:
This is intended as a HELP answer not the total absolute answer but I could not write the code in a comment. I am not asking for votes (for those who just can't wait to downvote me). I have created your tables and tried a UNION query on raw sql. I got correct results. I dont have laravel installed, but maybe you could try a UNION query in Laravel.
https://laravel.com/docs/5.4/queries#unions
select count(count_downloads.user_id)
from count_downloads
join items
on items.id = count_downloads.items_id
UNION
select count(count_loves.user_id)
from count_loves
join items
on items.id = count_loves.items_id

how to orderby before groupby columns products table and show unique and available products

I've a problem in laravel query:
I wanna to order by before group by of same columns,
for example:
Products table
id ....... cat_id ....... color_id ....... count<br>
---------------------------------------------------------<br>
1 ........... 27 ............... 3 ............... 0
<br>
2 ........... 27 ............... 7 ................ 3
<br>
3 ........... 27 ............... 3 ................ 10
<br>
4 ........... 27 ............... 3 ................ 2
now: I wanna down result with first orderby 'count' so groupby 'cat_id,color_id':
id ....... cat_id ....... color_id ....... count<br>
---------------------------------------------------------<br>
3 ........... 27 ............... 3 ............... 10
<br>
2 ........... 27 ............... 7 ................ 3
Assuming your Query looks like
SELECT id, cat_id, color_id, count FROM products
and count is a value from the DB, you can just combine GROUP BY and ORDER BY statements:
SELECT id, cat_id, color_id, count FROM products GROUP BY cat_id, color_id ORDER BY count
With this Query a lot of results are lost. If you want to combine the values for lets say count you could use GROUP_CONCAT:
SELECT id, cat_id, color_id, GROUP_CONCAT(count) FROM products GROUP BY cat_id, color_id ORDER BY count
With this Query, you will still get all relevant information, but for every entry in columns cat_id and color_id you will get a comma-seperateted string of the values for count.
Here some links for further information from w3schools:
GROUP BY
ORDER BY
please try this
select pr_l.*
from products pr_l
inner join (
select
cat_id, color_id,max(count) as count
from products
group by `cat_id`,`color_id`
) pr_r
on pr_l.count = pr_r.count and pr_l.cat_id = pr_r.cat_id and pr_l.color_id = pr_r.color_id
order by count desc
normally 'order by' before 'group by' is not working . so that i have used inner join for products table
left products table has all records and right products table has maximum count row with group by cat_id and color_id
for laravel sql syntax
$products = $products->select(DB::raw('pr_l.*'))->from(
DB::raw('inner join (
select
cat_id, color_id,max(count) as count
from products
group by `cat_id`,`color_id`
) pr_r')
)->where(pr_l.count = pr_r.count and pr_l.cat_id = pr_r.cat_id and pr_l.color_id = pr_r.color_id)->orderBy('count', 'desc');
how to convert:
select l.*
from products l
inner join (
select
cat_id, color_id,max(count) as count
from products
group by `cat_id`,`color_id`
) r
on l.count = r.count and l.cat_id = r.cat_id and l.color_id = r.color_id
order by count desc
to laravel elequent syntax looklike down:
$products = $products->select(DB::raw('l.*'))->from(
DB::raw('inner join (
select
cat_id, color_id,max(count) as count
from products
group by `cat_id`,`color_id`
) r')
)->where(l.count = r.count and l.cat_id = r.cat_id and l.color_id = r.color_id)->groupBy(['products_id','color'])->orderBy('count', 'desc');

SQL Join raw query issue on similar coloumn

Here is my report table
report
id user_id field_tech_id
1 1 4
2 3 6
And User table is
user
id name user_type
1 raj 1
3 ram 1
4 anthony 2
6 kumar 2
Here in coloumn user_type 1 for user and 2 for field_tech
How can i do join and get the username and field tech name of the orders
I tried like
$data = Report::select('user.name as user_name')
->leftjoin('users','users.id','=','report.user_id')
->get();
But when i try
$data = Report::select('user.name as user_name')
->leftjoin('users','users.id','=','report.user_id')
->leftjoin('users','users.id','=','report.field_tech_id')
->get();
How can i get the user name and field tech name ?
try this :
$data = Report::select('user.name as user_name')
->leftjoin('users as users1','users.id','=','report.user_id')
->leftjoin('users as users2','users.id','=','report.field_tech_id')
->select('users1.*,users2.*)
->get();
If you can pass the whole SQL query then this should work:
SELECT u.name as user_name, r.field_tech_id
FROM user u
LEFT JOIN report r
ON u.id = r.user_id

How can i use sql count in these multiple tables?

I am still a php/mysql newbie and I am working on mysql table relationship concept and i am having an issue with using mysql count in multiple table. Here is my db structure.
**product table**
id product_name product_img groupeid
1 Sneaker Mark sneaker_adi.png 1
2 bag Eric bageric.png 2
3 Sneaker Etoi sneakeretoi.jpg 1
**groupe table**
group_id group_name
1 men
2 women
**category table**
catid catname
1 sneaker-shoes
2 bag-woman
**productcategory table**
prod_id cat_ID
1 1
2 2
3 1
What i want to do is to determine the number of sneaker-shoes using mysql.
We can see that the number of sneaker-shoes in the db is 2.
But how can i use **count()** in these multiple tables.
I tried like this;
$sql = "SELECT COUNT(*) product.id,product_name,catname FROM product INNER JOIN productcategory ON product.id = prod_id INNER JOIN category ON catid = cat_ID WHERE catname='sneaker-shoes'";
i got error like:
Fatal error: Call to a member function execute() on a non-object in C:\wamp\www\kbashopping\Homme\index.php on line 32
Hope i exposed the issue clearly, any help and assistance will be appreciate
Thanks
If you are looking only for the count, mention only the count phrase in the Select clause.
Change :
SELECT COUNT(*) product.id,product_name,catname FROM
to :
SELECT COUNT(product.id) FROM
SELECT count (pc.cat_ID) FROM productcategory pc inner join category c on c.catid = pc.cat_ID where c.catname = 'sneaker shoes';
This will build a temporary table in mysql that joins category and product category but only including results where the catname is sneaker shoes. Then it selects a column to run the count operation on, and returns the result of count.

Laravel SQLSTATE[42000]: Syntax error or access violation

I am new to laravel and im stuck with my relationshops what looks like the following
Categories
id name slug
-----------------------------------------------------------------
3 Location location
4 Outfits outfits
5 Other other
sub_categories
id category_id name slug
-----------------------------------------------------------------------------
12 3 Club club
13 3 Home / Hotel home-hotel
14 3 Outdoor outdoor
15 3 Studio studio
16 4 Bikini / Swimwear bikini-swimwear
17 4 Dress dress
19 4 Jeans jeans
35 5 Dancing dancing
Category model
<?php
class Category extends Eloquent {
public $timestamps = false;
public function subcategory()
{
return $this->belongsToMany('subcategory', "sub_categories");
}
}
And i get the following error
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'sub_categories' (SQL: select `sub_categories`.*, `sub_categories`.`category_id` as `pivot_category_id`, `sub_categories`.`subcategory_id` as `pivot_subcategory_id` from `sub_categories` inner join `sub_categories` on `sub_categories`.`id` = `sub_categories`.`subcategory_id` where `sub_categories`.`category_id` = ?) (Bindings: array ( 0 => 1, ))
Could please someone point out what I am doing wrong?
you should give different aliases names to same table
change this
inner join `sub_categories`
to
inner join `sub_categories` as sc
^^--//-this alias use it instead of sub_categories
in your query it will be
select `sub_categories`.*, sc.`category_id` as `pivot_category_id`, sc.`subcategory_id` as `pivot_subcategory_id` from `sub_categories` inner join `sub_categories` sc on sc.`id` = `sub_categories`.`subcategory_id` where `sub_categories`.`category_id` = ?) (Bindings: array ( 0 => 1, )
Example:
select * from table1 as t1
inner join table1 as t2
on t1.id = t2.id
Clarification of your error: Not unique table/alias
you are joining same table without aliases to different between them.
The problem looks like that two tables are mapped to the same name sub_category at once.
A many-to-many relationship requires 3 tables (category/subcategory/category_subcategory) which need distinct names. If two of the tables get mapped with the same name, you'll get the error you're showing.
Change one of the mappings, and you should be up and running.

Categories