3 models query data in cgridview using yii framework - yii

how can we accomplish the below query result in cgridview using 3 models.?
select a.id,
a.name,
b.group_id,
c.id,
c.client_id,
c.title
from users_phone_numbers a,
phone_number_group_assignment b,
client_groups c
where a.id = b.phone_number_id
and b.group_id=c.id;
plz reply thanks

Use CArrayDataProvider
$rawData=Yii::app()->db->createCommand('... query ...')->queryAll();
$dataProvider=new CArrayDataProvider($rawData, array(
'id'=>'a.id',
'sort'=>array(
'attributes'=>array(
'a.name, b.group_id, ...',
),
),
));
Pass $dataProvider as the DataProvider to your grid view.

Related

How can I correct this syntax error in this sql query with array_agg

I am trying to include order by in line 35 and 43 in the query below. I want to order the option and field models by order column, ascending. But I am getting a syntax error:
syntax error at or near "AS"
LINE 42: )) AS "fields"
I am using postgresql. The full code is below:
WITH qs AS (
SELECT
"issQuestion".*,
array_agg(jsonb_build_object(
'id', "responses"."id",
'questionId', "responses"."questionId",
'title', "responses"."title",
'createdAt', "responses"."createdAt",
'updatedAt', "responses"."updatedAt"
)) AS "responses"
FROM question AS "question"
LEFT OUTER JOIN "question_response" AS "responses" ON "question"."id" = "responses"."questionId" AND "responses"."supervisionId" = 59
WHERE "question".id = 135
GROUP BY "question".id, "question".title, "question"."createdAt", "question"."updatedAt"
), qs_op AS (
SELECT
qs.*,
array_agg(jsonb_build_object(
'id', "options"."id",
'text', "options"."text",
'score', "options"."score",
'order', "options"."order"
)) AS "options"
order by 'order' ASC,
array_agg(jsonb_build_object(
'id', "fields"."id",
'name', "fields"."name",
'label', "fields"."label",
'order', "fields"."order",
'isNumeric', "fields"."isNumeric"
)) AS "fields"
order by 'order' ASC,
FROM qs
LEFT OUTER JOIN "question_option" AS "options" ON qs.id = "options"."questionId"
LEFT OUTER JOIN "question_field" AS "fields" ON qs.id = "fields"."questionId"
GROUP BY qs.id, qs.title, qs."createdAt", qs."updatedAt", qs."responses"
), qs_op_2 AS (
SELECT
qs_op.*,
array_agg(jsonb_build_object(
'id', "ft"."id",
'name', "ft"."name"
)) AS "associatedFacilityTypes"
FROM qs_op
LEFT OUTER JOIN ( "question_facility_type" AS "iqf" INNER JOIN "fac_type" AS "ft" ON "ft"."id" = "iqf"."facilityTypeId") ON qs_op.id = "iqf"."questionId"
GROUP BY qs_op.id, qs_op.title, qs_op."createdAt", qs_op."updatedAt", qs_op."responses", qs_op."options", qs_op."fields"
)
SELECT * FROM qs_op_2
ORDER BY qs_op_2.id;
It looks like the ORDER BY corresponds to the data used inside ARRAY_AGG() function. In which case it must be placed inside the function (complete syntax is described here):
array_agg(jsonb_build_object(
'id', "options"."id",
'text', "options"."text",
'score', "options"."score",
'order', "options"."order"
) ORDER BY "options"."order" ASC) AS "options"

SQL query to get the author who having maximum number of post (custom post type) in Wordpress

I would like to get the author information based on a particular criteria. The criteria is that, would like to get the author who having maximum number of post(custom post type).
This is the code I am trying to get the result.
$author_query = new WP_User_Query(array (
'orderby' => 'post_count',
'order' => 'DESC',
));
$authors = $author_query->get_results();
foreach ( $authors as $author ) {
echo $author->ID;
echo $author->display_name;
}
I solved this using custom sql query. Posting the answer for others who need it in the future.
SELECT SQL_CALC_FOUND_ROWS wp_users.ID,post_count FROM wp_users RIGHT JOIN (SELECT post_author, COUNT(*) as post_count FROM wp_posts WHERE ( ( post_type = 'custom-post-type' AND ( post_status = 'publish' ) ) ) GROUP BY post_author) p ON (wp_users.ID = p.post_author) WHERE 1=1 ORDER BY post_count DESC

Convert SQL Query to LINQ-to-SQL

I need help converting SQL query to LINQ to SQL
select top 5 customer_id, customer_name, product_id
from Customer
Join Product on product_id = product_id
where (customer_active = 'TRUE')
order by checksum(newid())
How can I do that in LINQ to SQL. Thanks
This was solved. Thanks to 'CodeNotFound' for this answer
https://stackoverflow.com/a/43850748/1655774
db.Customer.Where(p => p.customer_active == true).Select(p => new CustomerViewModel
{
Customer_id= p.customer_id,
Customer_name = p.customer_name,
Product_id = p.Product.product_id
}).OrderBy(c => SqlFunctions.Checksum(Guid.NewGuid())).Take(5).ToList();
try this code
( from p in Customer
join q in Product on p.product_id equals q.product_id
join q in Product on p.product_id equals q.product_id
where customer_active ==true select new
{
customer_id=p.customer_id,
customer_name=p.customer_name,
product_id=q.product_id
}).OrderBy(c => SqlFunctions.Checksum(Guid.NewGuid())).Take(5).ToList();
you should use this way to remove Boolean condition and reduce code
if you need to check bool condition in Ef
1.For True Condition
db.Customer.Where(p => p.customer_active).select(m=>m).tolist();
1.For False Condition
db.Customer.Where(p => !p.customer_active).select(m=>m).tolist();
just for suggestion

NHIbernate: Setting up subquery to use property value from outer query

I have the following sub/criteria:
var sq = DetachedCriteria.For<Title>()
.CreateAlias("Genres", "genre")
.Add(Restrictions.IsNull("genre.ParentId"))
.SetProjection(Projections.Property<Genre>(g=>g.Name));
var q =
session.CreateCriteria(typeof(Title))
.SetProjection(
Projections.Alias(Projections.SqlFunction("array", null, Projections.SubQuery(sq)), "TopLevelGenre"),
Projections.Property<Title>(t1=>t1.Id)
)
.SetMaxResults(5);
Which results in the following SQL query:
SELECT array((SELECT this_0_.title as y0_
FROM title this_0_
inner join title_genre genres3_
on this_0_.title_id = genres3_.title_id
inner join genre genre1_
on genres3_.genre_id = genre1_.genre_id
WHERE genre1_.parent_id is null)) as y0_,
this_.title_id as y1_
FROM title this_
limit 5 /* :p1 */
How do I set it up so that my subquery uses the value of a property from the outer query? For example, I'd like for the subquery to filter by the title_id value. Is there anything in NHibernate that allows me to project a property value to the subquery?
Thanks!
Turns out I was close. All I had to do was create an alias for Title and use that in the Where clause of my subquery.
Title title = null;
c = Session
.QueryOver(() => title)
....
.SelectList(list => list
.Select(Projections.Alias(Projections.SqlFunction("array", null, Projections.SubQuery(sq.Where(tt => tt.Id == title.Id))), "TopLevelGenre"))
);
Hope that helps someone..

LINQ 2 SQL: top 1 post per member ordered by created data

Okay so I have the sql to work this out as asked in the stackoverflow question here.
Does anyone know how to translate this to linq 2 sql? I'm guessing that the easiest way is to add a stored procedure, but I am curious to see if it can be linq-a-fied :P
select p.*
from post p join
(
select memberId, max(createdDate) as maxd
from post
group by memberId
) as p2 on p.memberid = p2.memberid and p.createdDate=p2.maxd
order by p.createdDate desc
I'm not totally sure this is the most efficient way to run this query (maybe it is, but I've got a feeling there's a better way. Haven't thought of it yet).
from
post in Nt_Post
join
memberdates in (
from
p_inner in Nt_Post
group
p_inner by p_inner.MemberId into grouped
select new {
MemberId = grouped.Key,
ActivationDate = grouped.Max(m => m.ActivationDate)
})
on
new { post.MemberId, post.ActivationDate }
equals
new { memberdates.MemberId, memberdates.ActivationDate }
orderby post.ActivationDate
select post;
Here is the query working within LinqPad on my database (not createdDate is actually activationDate and the Post table is Nt_Post. Thanks to Rex M for commming up with the solution :P
var q =
from
post in Nt_Post
join
memberdates in (
from
p_inner in Nt_Post
group
p_inner by p_inner.MemberId into grouped
select new {
MemberId = grouped.Key,
ActivationDate = grouped.Max(m => m.ActivationDate)
})
on
new { post.MemberId, post.ActivationDate }
equals
new { memberdates.MemberId, memberdates.ActivationDate }
orderby post.ActivationDate
select post;
q.Dump();
The sql generated is:
SELECT [t0].[Id], [t0].[Title], [t0].[Teaser], [t0].[Text], [t0].[ActivationDate], [t0].[CreatedDate], [t0].[LastModifiedDate], [t0].[IsActive], [t0].[Permalink], [t0].[MemberId], [t0].[HomePageVisibility], [t0].[Image], [t0].[ImageContentType], [t0].[HasNotifiedRTR]
FROM [nt_Post] AS [t0]
INNER JOIN (
SELECT MAX([t1].[ActivationDate]) AS [value], [t1].[MemberId]
FROM [nt_Post] AS [t1]
GROUP BY [t1].[MemberId]
) AS [t2] ON ([t0].[MemberId] = [t2].[MemberId]) AND ([t0].[ActivationDate] = [t2].[value])
ORDER BY [t0].[ActivationDate]