How to get data from another table using ID from another table - php

I would like to get a data from a table to another table using it's primary key.
products_table:
id name type_id date_added
1 item1 2 1234
2 item2 2 5678
3 item3 1 0000
product_type_table:
id type_name
1 type1
2 type2
3 type3
I am querying the first table using this code:
Products::select('name','type_id')->where('id',$id)->get()
Now, how do I automatically get the type_name from the product_type_table using the type_id from the products_table?

As Jack Skeletron pointed out, the Laravel documentation has examples for joining 2 or multiple tables.
In your case
$products = DB::table('products_table')
->join('product_type_table', 'products_table.type_id', '=', 'product_type_table.type_id')
->select('products_table.name, products_table.type_id')
->where('id', $id)
->get();

you can use left join.
DB::table('product_type_table')
->leftJoin('products_table', 'product_type_table.id', '=', 'products_table.type_id ')->where('product_type_table.id',$id)
->get();

In Product Model add Below code for joining 2 tables:
use App\Models\ProductType;
public function type()
{
return $this->belongsTo(ProductType::class);
}
and change the line:
Products::select('name','type_id')->where('id',$id)->get()
to
Products::select('name','type_id')->with(['type' => function($q){
return $q->select('type_name');
}])->where('id',$id)->get()
Hope this works for you.

Related

Laravel wherenotexists returning null

I have the following piece of code
$not_paid = Tenant::where('property_id', $property_id)
->whereNotExists(function ($query) use ($property_id) {
$query->select('user_id')
->from('rent_paids');
})
->get();
which is supposed to get all the tenants in a certain property, look them up in the rent_paids table and return the users who are not in the rent_paids table, as follows:
tenants table
Id
user_id
property_id
1
1
1
2
2
1
3
3
1
rent_paids
Id
user_id
property_id
amount_paid
1
1
1
3000
I want to be able to return the users in the tenants table and not in the rent_paids table. In this case, users 2 and 3. But the above code returns an empty array.
You're missing the where clause to tie it back to the original table.
$not_paid = Tenant::where('property_id', $property_id)
->whereNotExists(function ($query) use ($property_id) {
$query->select('user_id')
->from('rent_paids')
->whereColumn('tenants.user_id', '=', 'rent_paids.user_id');
})
->get();

how to find same id and group and count the same id on different days

currently i have a database structure like this :-
what i want to create (in laravel eloquent) is first get user_id and date_access. then based on the dates for example on the 2018-03-07 the are 3 rows, so user_id 1 have 2 times so = 2018-03-07 => 2
this is because it should group same user_id together to make it 1 and another user_id plus together..
how can i do this?
Can you try this:
$collections = DB::table('my_table')
->select(DB::raw('count(user_id) as users'))
->groupBy('date_access')
->get();

Codeigniter Active Records get where

The documentation only mentions these parameters.
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
Is the above absolute? or is there more details hidden somewhere in the codeigniter userguide?
I would like to know how to only return rows of a specific column.
For example, on a Person table. I only wanted the name of the row in person table with the person_id of 1. Or for example, on children table, i want to get only the rows for child_name of parent_id = 1.
$this->db->get_where('person', array('person_id' => 1))->result_array();
Say Children table has 4 columns.
Person_id Child_id Child_Name and Child_age
So 1 person id can have as many children. Say the values are.
1 1 john 4
1 2 peter 3
1 3 michael 7
2 4 noah 10
So i only want the name of the children of person_id = 1.
You can do method chaining as such:
public function get() {
return $this->db->select('person_name')
->get_where('person', array('person_id' => 1))
->result_array();
}
Or just simply
public function get() {
$this->db->select('person_name');
return $this->db->get_where('person', array('person_id' => 1))->result_array();
}
But the get_where or similar function of CI query builder don't have in-built select statements other than $this->db->select('somename')

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

yii2:autofill on multiple condtions

I have models/tables as follows:
table room_category
id room_category
1 Classic
2 Deluxe
table room_charges
id room_category room_name room_charges
1 1 c1 600
2 2 d1 800
table ipd_charges
id doctor room_category charges_cash charges_cashless
1 1 1 200 300
2 1 2 300 400
table patient_detail(patient_admission)
id patient_name tpa_name(if not null, equivalent to charges_cashless)
1 1 Null
2 2 1
table daily_ward_entry
id patient_name room_name(id) doctor_name(id) charges ( from ipd_charges)
1 1 1 1 200
2 2 2 1 400
Now there is a dropdown field in daily_ward_entry table for doctor. When I select the drop-down field the charges field needs to be autofilled.
I achieve this using Jason and ajax with the following code without taking into account the room_category. but the charges vary for room_category.(this is only working after saving the record, I prefer if there is someway to pull the charges before save.)
Here is my code in the controller:
public function actionChargesCash($id){
$model = \app\models\IpdCharges::findOne(['doctor'=>$id]);
return \yii\helpers\Json::encode(['visit_charges'=>$model->charges_cash]);
}
public function actionChargesCashLess($id){
$model= \app\models\IpdCharges::findOne(['doctor'=>$id]);
return \yii\helpers\Json::encode(['visit_charges'=>$model->charges_cashless]);
}
I have also tried this variaton:
public function actionChargesCash($id){
$model = \app\models\IpdCharges::find()
->where(['doctor'=>$id])
->andwhere(['room_category'=>'daily_ward_entry.room_name'])->one();
If I replace the 'daily_ward_entry.room_name' with room_name id like 3 or 6, I am getting the result, which means I am not using the correct syntax for referring the column from current table.
How can I include the condition for room_name in the above code?
Thanks in advance for your valuable help.
daily_ward_entry.room_name is meaningless without any relation or join or sub-query. Actually, the query does not know the daily_ward_entry.
Suggestions:
1- Create a relation and use with or Join With
2- Create a query with Join of daily_ward_entry and ipd_charges on room_name=room_category
3- Create a query with a sub-query, to find all|one IpdCharge(s) that have room_category in SELECT room_name FROM daily_ward_entry
All of above suggestions satisfy your requirements.
Another important note:
andWhere()/orWhere() are to apply where to the default condition.
where() is to ignore the default condition
I don't see any default condition (Overridden Find()), So, there is no need to use andWhere, Just:
where(['doctor'=>$id,'room_category'=>3,...])
Would be sufficient.

Categories