I have a join where i have a many to many relationship between categories and courses....I use multiple join in CodeIgniter with Active Record. My code looks like this:
$query = $this->db->select('*')
->from('subscriptions')
->where('subscriptions.user_id', $user_id)
->join('courses', 'courses.id=subscriptions.course_id')
->join('course_categories', 'course_categories.course_id=courses.id')
->join('categories', 'categories.id=course_categories.category_id')
->join('tutor_profiles', 'tutor_profiles.id=courses.tutor_id')
->get();
I have a problem retrieving multiple categories for 1 course...i want to have something like categories = array(JOIN RESULT). I mean i want to retrieve the results from the join of the categories in 1 sql variable that is an array and loop the results after.
How can I do this? Or do I need to make 2 queries?
You should try to serialize your result and save it in db
Related
I'm using Laravel 5 and I need to know the number of books by category, these data I will use on google charts.
I have the code below that I use to find out the number of users by sex. However, the data is in the same table.
$data = DB::table('books')
->select(
DB::raw('category_id as category'),
DB::raw('count(*) as number'))
->groupBy('category')
->get();
$array[] = ['Category', 'Number'];
foreach($data as $key => $value)
{
$array[++$key] = [$value->category->name, $value->number];
}
$test = json_encode($array);
Using the same logic as above, how can I get the number of books by category?
I have the Books table:
ID | Name | ID_CATEGORY
1 Laravel 20
2 Java 20
Category table :
ID | Name
20 Programming
Could you help me in this situation?
You should just group by your ID_CATEGORY column instead of sex.
If you want to construct such array as before, you probably want the name of category. That would be easy if you used Eloquent. You would have $value->category->Name_Category available. If you want those preloaded instead of a query for every value, just add ->with('category') to the query and you'll have it.
If you are not using Eloquent, you should just load the category table separately, key it, and use $categories[$value->ID_CATEGORY]->Name_Category.
Other comments
DB::raw('sex as sex') is equivalent to sex.
++$key seems redundant, you could just push to the end by assigning to $array[].
Array with a header row is not very JSON. Typically you'd have key:value pairs all of the time.
You can construct the array using collection methods.
If you don't have good reasons for the opposite, you should stick to Laravel naming conventions.
I would probably not create an array myself, but do your example as something like this:
$stats = User::select('sex', DB::raw('count(*) as number'))
->groupBy('sex')
->get();
$stats->setVisible(['sex', 'number']);
return $stats;
I'm working on a laravel application Where I have two very similar QueryBuilder but producing different result in both conditions.
Query 1:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->whereRaw('feed.active <> agents.feed_status')
->pluck('id');
dd(count($ids)); // print 485236
Query 2:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->where('feed.active', '<>', 'agents.feed_status')
->pluck('id');
dd(count($ids)); // print 4259
I would like to know the key difference between these two QueryBuilder. Why is it producing different results, although it seems identical?
And which query returns the correct result? if I would like to find the records from agents where feed_status is not equel to feed.active.
it seem I have got the clarification. Howevere I would like to share my R&D here. Incase if anyone else got the same problem.
I have printed the raw query and get where() seems consider the third parameter as string compare instead of field compare. That's why seems the result is different.
However when we run the query with whereRaw() it's treated this as table field comparision.
Laravel Code:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->whereRaw('feed.active <> agents.feed_status')
->pluck('id');
MySql Query:
"select * from `agents` left join `feed` on `agents`.`identifier` = `feed`.`identifier` where feed.active <> agents.feed_status"
# where feed.active <> agents.feed_status
Laravel Code:
$ids = $this->model->leftJoin('feed', 'agents.identifier', '=', 'feed.identifier')
->where('feed.active', '<>', 'agents.feed_status')
->pluck('id');
MySql Query:
"select * from `agents` left join `feed` on `agents`.`identifier` = `feed`.`identifier` where `feed`.`active` <> 'agents.feed_status'"
# where feed.active <> 'agents.feed_status'
Yes, the results were meant to be different.
As where method compares a column with a literal value
->where('table.column', 'cond', 'value')
If you are looking to make comparisons in two columns without using whereRaw method; you should instead use whereColumn method
->whereColumn('table1.column1', 'cond', 'table2.column2')
I've looked at other questions, and I am not certain this is the same as previously asked questions.
Basically, I have three queries in succession. Query 1 results are passed to Query 2, and Query 2 results are passed to query 3, and write query 3 results to a file.
'select convert(char(10),max(paydate),101) from DATA.dbo.payment where status like 'PAID%'
'select distinct groupkey from custom.dbo.ediX091Header_abc where CheckIssue = '<results from query 1>' and status = 'Go'
'select max(GroupKey) from dbo.ediFuncGroup_abc' where GroupKey = '<results from query 2>'
Write any results from query 3 to an output file.
Thanks in advance
You don't need to run all three queries one after the other. You can pretty easily join the tables from the second and third queries. Then use the first query as a subquery to filter the results. Something like this.
select MAX(GroupKey)
from dbo.ediFunctionGroup_abc fc
join custom.dbo.ediX091Header_abc h on h.GroupKey = fc.GroupKey
where h.status = 'Go'
and h.CheckIssue = (select CONVERT(char(10), max(paydate)) from DATA.dbo.payment where status like 'PAID%')
I have the following database scheme on MySQL and I would like to retrieve all elements for a speciic id.
So for instance, I would like to retrieve cities, categories, departments linked to the coupon_id=1 (and other fields).
I wrote the following SQL query but unfortunatelly could not get the desired result.
SELECT cc_coupon.id_coupon as idCoupon,
cc_coupon.condition_coupon,
cc_coupon.description,
cc_coupon.type_coupon,
cc_coupon_by_categorie.id_categorie,
cc_categorie.categorie as category,
cc_annonceur.raison_sociale,
cc_coupon_active_in_cities.id_ville as ville_slug,
cc_villes_france.ville_slug,
cc_villes_france.ville_nom_departement,
cc_villes_france.ville_departement
FROM cc_coupon,
cc_coupon_by_categorie,
cc_categorie,
cc_annonceur,
cc_coupon_active_in_cities,
cc_coupon_active_in_departments,
cc_villes_france
WHERE cc_coupon.id_coupon = cc_coupon_by_categorie.id_coupon
and cc_categorie.id_categorie = cc_coupon_by_categorie.id_categorie
and cc_coupon.id_annonceur = cc_annonceur.id_annonceur
and cc_coupon.id_coupon = cc_coupon_active_in_cities.id_coupon
and cc_villes_france.id_ville = cc_coupon_active_in_cities.id_ville
and cc_villes_france.ville_departement = cc_coupon_active_in_departments.ville_departement
and cc_coupon.id_coupon = 1
and cc_coupon_active_in_cities.id_coupon = 1
and cc_coupon_active_in_departments.id_coupon = 1
Thanks for your help.
I think you should use the on and not where when you want to join two tables. When you want to specify other conditions use where clause.
I have a select query in Mysql table to fetch related table with a duplicate values in a specific column(date).This will successfully display columns and its foreign keys if it has duplicate values in a column.Example two rows same value of (2014-11-10) in a date column
mysql>select man_id,date_created,count(date_created) as count
from collections
group by man_id,date_created
having count(date_created) > 1;
I want this query to convert to Doctrine query since I am using symfony 1.4 as a framework
public function getDuplicateDatePayment() {
$q = $this->createQuery()
->select('man_id','date_created','count(date_created) as count')
->from('Collections')
->groupBy('man_id','date_created')
->having('COUNT(c.date_created) > 1');
return $q->execute();
}
SELECT c.id AS c__id, c.man_id AS c__man_id FROM collections c GROUP BY c.man_id HAVING count(c.date_created) > 1 //result 1 row
why does doctrine query does not display results as expected?How to convert said doctrine query so that it will display result similar to SQL?
//result 1141 rows
update
Collections table is related to Man table in a one to many relationship.Do i have to use innerJoin for this?
After two days of trying,searching for an answer, I finally found a solution to my problem.
SELECT c.id AS c__id, c.man_id AS c__man_id FROM collections c GROUP BY c.man_id HAVING count(c.date_created) > 1
The problem of above sql result from doctrine is ,it does not include 'c.loan_id' in groupBy clause,even though I include it in groupBy clause.The solution is ,just add a separated addGroupBy clause ..And now its working.cheers..
public function getDuplicateDatePayment() {
$q = $this->createQuery()
->select('c.man_id','c.date_created','count(c.date_created) as count')
->from('Collections')
->groupBy('c.man_id')
->addGroupBy('c.date_created')
->having('count(c.date_created) > 1');
return $q->execute();
}