in my project i have 4 tables. One called Calls, Projects, Products and Users.
Calls has 2 FK (project_id and user_id) and Projects has one FK (product_id).
I'm trying to query the table Calls and I want to know the amount of calls for each product has been received from each operator.
I'm trying to query something like this:
[{"name":"User1","Project1":"120","Project2":"10,"Project3":"140...}
{"name":"User2","Project1":"80","Project2":"60,"Project3":"14...}]
I am guessing when you mean operator you mean user
$this->db->select('count(P.product_id) as total_product ,CL.project_id, CL.user_id, P.project_name')
->from('Calls CL')
->join('Projects P', 'P.project_id=CL.project_id')
->group_by('CL.project_id, CL.user_id')
->get();
Now your can write a php script to loop through your result to make the json
$index = 0;
$user_data = array();
$user_key = array();
foreach ($result as $row) {
if(!isset($user_key[$row['user_id']])){
$user_key[$row['user_id']] = $index;
$index++;
}
$user_data[$user_key[$row['user_id']]]['user_name'] = $row['user_name'];
$user_data[$user_key[$row['user_id']]][$row['project_name']] = $row['total_product'];
}
I did not tested the code but it should work
Related
i want to ask about sql in postgresql, i got data from join with 3 table, i got the result but i got multiple data like this image
result
and here my sql code in postgresql
select users.* from users inner join model_has_roles on model_has_roles.model_id = users.id
left join roles on roles.id = model_has_roles.role_id where roles.name not in ('job-seeker') order by users.name asc
how to fix this query where i got the multiple data only 1 data to show.
and i want this sql to implement to laravel query and here my code now
public function getAccountList(){
$req = app(Request::class);
// $getAccount = User::query();
$getAccount = User::join('model_has_roles', function($join) {
$join->on('users.id', '=', 'model_has_roles.model_id');
})->leftJoin('roles', function($join){
$join->on('model_has_roles.role_id', '=', 'roles.id');
});
$getAccount->whereNotIn('roles.name', ['job-seeker']);
if ($q = $req->query('q')) {
$searchTerm = trim(strtolower($q));
$getAccount->whereRaw(
'LOWER(users.name) like (?) or LOWER(users.email) like (?)',
["%{$searchTerm}%", "%{$searchTerm}%"]
);
}
// $getAccount->get()->unique('name');
$getAccount->select(['users.*']);
$paginator = $this->pagination($getAccount);
return $this->paginate($paginator, new UserTransformer);
}
how to fix the query only 1 data to show not the multiple same data. thank you for helping me. God Bless You
use distinct()
$data = DB::table('test')->[your query builder]->distinct()->get();
Laravel Query Builder Docs
Just change a bit to make it related to your query builder
I am creating a page that displays info on equipment that has been scanned into and out of my office. The way I want it to display is
Equipment Name User(Headtech) Event used Returned(Y/N)
The problem is the SQL tables are everywhere and joining them all is proving to be difficult. There needs to be a chain going through three tables to get the Head tech name, this was not of my design and I can not change it.
What I currently have
$select = mysqli_query($con, "SELECT *
FROM equipment
JOIN pay
ON pay.eventid = equipment.eventid
JOIN personnel
ON personnel.workerid = (pay.eventid WHERE role = 'aht')
JOIN events
ON events.id = equipment.eventid
WHERE status='3'
ORDER By timeOut DESC");
while($row = mysqli_fetch_array($select)) {
$name = $row['name'];
$timeIn = $row['timeIn'];
$timeOut = $row['timeOut'];
$eventID = $row['eventid'];
echo "<div><div class='rowBoxS'>$name</div>";
$htName = $row['personnel.first'] . " " . $row['perosnnel.last'];
echo "<div class='rowBoxS'>$htName</div>";
$event = $row['eventName'];
echo "<div class='rowBoxS'>$event</div>";
if ($timeOut > 0){
echo "<div class='rowBoxS'>$</div></div>";
}
else{
echo "<div class='rowBoxS'>Failed to return</div></div>";
}
This is clearly not working as intended, and I'm very aware that that is probably not how joining works especially with the pay.eventid WHERE role = 'aht' bit. I want to know if there is a proper way to approach this. I tried looking it up, but most people probably have clean databases they are working with and couldn't possibly run into this problem.
Edit:
All the tables are on the same server. The problem is if I want to get someone's name you need to use the eventid row from equipment on the pay table find that id, then through the 'role' row find the user with AHT role and then take that persons workerid into the personnel table where you can finally find the persons name.
I'm working on a Symfony2 using Doctrine.
I would like to know how to change the behavior of "findBy" functions when retrieving my entities.
For example, if you call "findAll()", it returns all products.
$entities = $em->getRepository('ShopBundle:Product')->findAll();
However, how to reduce the number of queries, because, by default, it will create a new query each time I want to get a member linked to a join column. So if I get 100 entities, it will process 101 queries (1 to get all entities and 1 by entity to get join column).
So today, I use createQuery() function by specifying the joins. Is there a way to configure something about findBy functions to skip createQuery method ?
Thanks in advance !
K4
You can fetch out this in below way
public function findUser() {
$query = $this->getEntityManager()
->createQuery('SELECT us.id as id, us.name as user_name FROM Bundle:User us');
try {
return $query->getResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
I am working in a School Management project.The structure is when i am adding any new item in my project i have a single graph table where every item is generating a unique Graph Id, now i am having Cart where user can buy a book from it and that Cart contains GraphId of the item.
My problem is i want to search all the tables in database where that Item GraphId match the graphId in every table it give me the json of whole row of the table in which it exits
var searchgraphId = from m in db.OfflineCarts select m;
searchgraphId = searchgraphId.Where(s => s.UserId == loginuserinfoid);
foreach (var c in searchgraphId)
{
graphId = c.ListOfGraphIds;
}
This i have done where it will find all the graph ids belongs to login userid and it will get its carts item and now how to proceed??
you have to search graph id in all tables individual
your search will be as like
var searchgraphIdInUser = from m in db.UserInfo where m.GraphId == graphId select m;
foreach (var c in searchgraphIdInUser )
{
var user = db.UserInfoId.Find(c.UserInfoId)
// delete the row data here
}
Let's say I do a simple query:
$products =
Yii::app()->db->createCommand()->setFetchMode(PDO::FETCH_OBJ)
->select('*')
->from('products')
->limit(9)
->queryAll();
Let's say there are 500 products in the database. Is there a way I can get YII to automatically return the total number (count) of products if the "limit" was included? Perhaps return an object like this:
$products->products = array( ... products ... )
$products->totalProducts = 500;
The problem is, if LIMIT is included, it will return items, and the count will therefore be 9. I want a solution whereby it will return the 9 items, but also the count of say 200 items if there were 200 items.
Why not an easy:
$сount = Yii::app()->db->createCommand('select count(*) from table')->queryScalar();
echo $count;
You'll either have to run two queries (a count(*) query without the limit and then the limited query) or you can send you can retrieve your products using CSqlDataProvider and let it do it for you. But it generally takes two queries.
Note: one of the nifty features in Yii 1.1.13 is that you can send your query builder command in to the CSqlDataProvider if you're going to be using a dataprovider. More information at on this pull request that fixed it. That way, you can both use the power of query builder while also being able to shift your data into a dataprovider. Previously you had to build your SQL statement manually or grab the queryText of the command.
Yii::app()->db->createCommand('select count(*) from tbl_table')->queryScalar();
Try to use execute() instead of query() because execute returns rows count.
example:
$rowCount = $command->execute();
You could try using COUNT like this:
$dbCommand = Yii::app()->db->createCommand("
SELECT COUNT(*) as count FROM `products`");
$data = $dbCommand->queryAll();
Hope that helps!
EDIT: You might find this useful too: CDataProvider
Try this -
$sql = Yii::app()->db->createCommand('select * from tbl_table')->queryAll(); //It's return the Array
echo count($sql); //Now using count() method we can count the array.