Codeigniter: relational database as Associative array like yii2 - codeigniter-2

In Yii2, consider two tables parent and child. If child has a relation to the parent then while writing join query it will produce result like
Parent[id => 1,
firstname => "John",
lastName => "Miller"
child => [id : 1,
address : some address,
contact number : some nubmer
]
]
But in Codeignitor it is displayed as the same as an output of mysql query. how to achieve my requirement in CodeIgnitor.
Thanks in Advance.

There are various methods to accomplish this.
You can do a query for the parent and then cycle the childs
$query_parent = $this->db->query($"
SELECT *
FROM parent
WHERE id = ?", [$parent_id]);
if($query_parent !== FALSE && $query_parent->num_rows() > 0)
{
$result_array_parent = $query_parent->result_array();
$query_parent->free_result();
foreach ($result_array_parent as $k_p => $v_p)
{
$query_child = $this->db->query($"
SELECT *
FROM child
WHERE id = ?", [$v_p['id']);
if($query_child !== FALSE && $query_child->num_rows() > 0)
{
$result_array_child = $query_child->result_array();
$query_child->free_result();
foreach ($result_array_child as $k_c => $v_c)
{
$result_array_parent[$k_p]["child_".$k_c] = $v_c;
}
}
}
}
Or do a Join query and then transform it to an array.

Related

How to Convert a LINQ Query Syntax to a Method Syntax? (with join and multiple selects) Issue: Where-no overloads for + 3 parameters

I am trying to understand lambda expressions with Linq but i struggle with the conversion. Below is the Linq Query syntax which works just fine.
var systemUsersPoor =
(from customer in customers
join distributor in distributors
on new { customer.Location }
equals new{ distributor.Location }
where customer.Location == "UK" &&
customer.Location==distributor.Location &&
customer.Supplier == "MoneyShits" &&
distributor.Products == "ShittyCrappyCraps"
orderby customer.Name
select new
{
customerName=customer.Name , customerLocation=customer.Location, customerSupplier=customer.Supplier,
distributorName=distributor.Name, distributorProducts=distributor.Products
}).ToList();
And then in here, i have my failed attempt to convert it into a Linq Method Syntax...All works untill the .Where statement..states that it does have no definition for my fields(.location,.Supplier) and distributor
var sysUserPoor2 = customers.Join //from customer in customers Join
(
distributors, //Join on distributors on customer.Location==distribution.Location
customer=> customer.Location, //Select the primary key (the first part of the "on" clause in an sql "join" statement
distributor =>distributor.Location, // Select the foreign key (the second part of the "on" clause)
(customer, distributor) => new //select statement
{
customerName = customer.Name,
customerLocation = customer.Location,
customerSupplier = customer.Supplier,
distributorName = distributor.Name,
distributorProducts = distributor.Products
}
)
.Where
(
customer => (customer.customerLocation == "UK") &&
(customer.customerSupplier == "MoneyShits"),
distributor => distributor.distributorProducts == "ShittyCrappyCraps",
(customer, distributor) => (customer.customerLocation == distributor.Location)
);
The query with the code below works, but i dont know how to add the rest somehow...:
.Where
(
customer => (customer.customerLocation == "UK") &&
(customer.customerSupplier == "MoneyShits")
)
Please try following.
var systemUsersPoor = customers.Join(distributors,
customer => customer.Location,
distributor => distributor.Location,
(customer, distributor) => new {customer, distributor})
.Where(x => x.customer.Location.Equals("UK") &&
x.customer.Location.Equals(x.distributor.Location) &&
x.customer.Supplier.Equals("MoneyShits") &&
x.distributor.Products.Equals("ShittyCrappyCraps"))
.OrderBy(x => x.customer.Name)
.Select(x => new
{
customerName = x.customer.Name,
customerLocation = x.customer.Location,
customerSupplier = x.customer.Supplier,
distributorName = x.distributor.Name,
distributorProducts = x.distributor.Products
}).ToList();

LINQ group by ID - Distinct by order

I have data in a generic list named "Assignment" as shown in the Original table. Want to group by ID and display only one record based on US-UK-India order.
The result should transform from first table to second as shown in the attached image.
Try this:
SQL like syntax.
from a in Assignments
group a by a.Id into gr select gr.FirstOrDefault()
Lambda expression:
Assignments
.GroupBy (a => a.Id)
.Select (gr => gr.FirstOrDefault ())
Try this, its works. I hope this is what you need.
var query01 = context.FirstTable
.GroupBy(p => p.ID
,(ky, el) => new { ky.Value , FirstCountry = el.Select(p => Country).Take(1)});
var Result = query01
.Join(context.FirstTable
, ul => new
{
Id = ul.Value
,Country = ul.FirstCountry.FirstOrDefault()
}
, fl => new
{
Id = (int)fl.ID
, Country = fl.Country
}
, (ul, fl) => new { fl }).ToList();

LINQ - optional/nullable where conditions

I do have the following LINQ query, selecting movies from my database that either contain the given search string or have one or more of the tags that I give to the function.
The problem is, that if the search string or the tags parameter are empty/null, I get no movies. The desired action however, is to get all the movies, so, if one parameter is null or empty, I don't want to apply it.
How can I do that?
public IEnumerable<Group<Genre, Movie>> GetMoviesGrouped(string search, List<Tag> tags)
{
var movies = from movie in Movies
where ( movie.Name.Contains(search)) && movie.Tags.Any(mt => tags.Any(t => t.ID == mt.ID))
group movie by movie.genre into g
select new Group<Genre, Movie> { Key = g.Key, Values = g };
....
}
Just for readability, I like to do it step by step
var movies = Movies;
if (!string.IsNullOrEmpty(search))
movies = movies.Where(m => m.Name.Contains(search));
if (tags != null && tags.Any()) {
var tagIds = tags.Select(m => m.ID);
movies = movies.Where(m => m.Tags.Any(x => tagIds.Contains(x.ID));
}
var result = from movie in movies
group ...
You can do something like this to skip the check if nothing is provided:
where (string.IsNullOrEmpty(search) || movie.Name.Contains(search)) &&
(!tags.Any() || movie.Tags.Any(mt => tags.Any(t => t.ID == mt.ID)))

ravendb count query not equal tolist count

ravendb query return different result for count method and tolist().count
query 1(return 9):
var count = session.Query<MobileForm,ByFormNameIndex>().Where(x => x.RequestType == RequestType.Db && x.BelongTo == oaname).ToList().Count;
query 2(return 44):
var count = session.Query<MobileForm,ByFormNameIndex>().Where(x => x.RequestType == RequestType.Db && x.BelongTo == oaname).Count();
index define:
public class ByFormNameIndex : AbstractIndexCreationTask<MobileForm>
{
public ByFormNameIndex()
{
Map = mobileForms => from form in mobileForms
select new
{
form.FormName,
form.BelongTo,
form.RequestType,
form.CreateTime,
form.Uuid
};
Analyzers.Add(x => x.FormName, "Lucene.Net.Analysis.PanGu.PanGuAnalyzer,PanGu.Lucene.Analyzer, Version=1.3.1.0, Culture=neutral, PublicKeyToken=null");
Indexes.Add(x => x.FormName, FieldIndexing.Analyzed);
Indexes.Add(x => x.BelongTo, FieldIndexing.NotAnalyzed);
Indexes.Add(x => x.RequestType, FieldIndexing.NotAnalyzed);
Indexes.Add(x => x.Uuid, FieldIndexing.NotAnalyzed);
}
}
query1 return the right count, so what's the differrent for this to method?show i new to rebuild the index to get the right result?
That is by design.
Count() will give you the total count.
ToList() gives you the first page only. And then you get the count on that.

Access any data that is not contained in grouped element

from teamBudget in TeamBudgets
where teamBudget.TeamID == 71002
join teamBroker in TeamBrokers on 71002 equals teamBroker.TeamID
join goal in Goals on teamBroker.GlobalBrokerID equals goal.GlobalBrokerID
group goal by goal.GlobalBrokerID into g
select new
{
// TeamID=teamBroker.TeamID,
// MTDGoal=teamBudget.Sum(t => t.Budget),
RevenueMTDCurrent = g.Sum(x => x.RevenueMTDCurrent)
}
Commented part is a problem. How to access any data that is not contained in grouped element?
you need to Group multiple fields then only you can access that data.
like
var result = from i in
(from uh in db.UserHistories
where uh.User.UserID == UserID && uh.CRMEntityID == (int)entity
select new { uh.ActionID, uh.ActionType, uh.ObjectID })
group i by new { i.ActionID, i.ActionType, i.ObjectID } into g
select new { g.ActionID, g.ActionType, g.ObjectID };
Hope this will help

Resources