PHP/Laravel: SELECT and JOIN two tables - php

I have three tables as shown below and trying to join the expenses and allowance table on customers. I have tried using the code below but it returns null on expenses and allowances. I tried inner JOIN as well but didn't work.
I have tables as below:
customers(id, user_id, full_name)
expenses(id, customer_id, name, amount)
allowances(id, customer_id, name, quantity)
And i tried using the code below but doesn't work.
$logs = Customer::query()
->select([
"customers.id",
"customers.full_name",
"expenses.name as expenses_name",
"expenses.amount as expenses_amount",
"allowances.name as allowance_name",
"allowances.quantity as allowance_quantity"
])
->join('expenses', function (JoinClause $join) {
$join->type = 'left outer';
$join->on('expenses.customer_id', 'customers.id');
})
->join('allowances', function (JoinClause $join) {
$join->type = 'left outer';
$join->on('allowances.customer_id', 'customers.id');
});
return $logs->toJson();
I want output as:
{
id:'',
full_name:'',
expenses:{{expenses_name, expenses_amount},{expenses_name, expenses_amount}},
allowances:{{allowance_name, allowance_quantity},{allowance_name, allowance_quantity}}
}

Use the following Code:
$logs = Customer::select([
"customers.id",
"customers.full_name",
"expenses.name as expenses_name",
"expenses.amount as expenses_amount",
"allowances.name as allowance_name",
"allowances.quantity as allowance_quantity"
])
->leftjoin('expenses', 'customers.id','=','expenses.customer_id')
->leftjoin( 'allowances','customers.id','=','allowances.customer_id')
->get();

You can also use eloquent relationship.
define relations in Customer Model
public function expenses()
{
return $this->hasMany(Expense::class);
}
public function allowances()
{
return $this->hasMany(Allowance::class);
}
get Customers with relationship
$logs = Customer::with(['expenses','allowances'])->get();

Related

how to join 4 tables in php laravel?

I Want to extract data from 4 tables .
like sname,cgpa,Group_Cgpa,Room_No and Hostel Name.
Relation of table is as follows.
AllotmentApps has : id,sname,cgpa and grpID (from Group id Table) columns.
Groups has : id,Group_CGPA
Room has : id, HostelID (From Hostel) and ResidentID (From Group id).
Hostels has: id, Name, Total_Rooms.
I'm facing problem in joining the tables. Join with AllotmentApps and Groups works fine, but problem occurs when I joined the Room and Hostel Table.
Join of AllotmentApps and Groups
public function FinalList()
{
$allot_apps = AllotmentApps::join('Groups','Groups.id','AllotmentApps.grpID')->orderBy('Groups.Group_CGPA', 'Desc')->get()->groupBy(
function($item) {
return $item->grpID;
}
) ->take(3);
Join of 4 Tables
public function FinalList()
{
$allot_apps = AllotmentApps::select('sname','cgpa','Group_CGPA','Hostel_Name')->join('Groups','Groups.id','AllotmentApps.grpID')->join('Hostels','Hostels.id','Hostels.HostelID')->join('Rooms','Rooms.id','Hostel.HostelID')->orderBy('Groups.id', 'Asc')->get()->groupBy(
function($item) {
return $item->grpID;
}
) ->take(3);
Try This
$allot_apps=AllotmentApps::select('AllotmentApps .sname','AllotmentApps .cgpa','Groups.Group_CGPA','tablename.Hostel_Name')
->join('Groups','Groups.id','=','AllotmentApps.grpID')
->join('Rooms','Rooms.ResidentID','=','Groups.id')
->join('Hostels','Hostels.id','=','Rooms.HostelID')
->orderBy('Groups.id', 'Asc')
->groupBy()
->get();
public function FinalList()
{ $capasity = Rooms::selectRaw('count(id) as c')->count();
$allot_apps = Rooms::select('Hostel_Name','Rooms.id','Groups.Group_CGPA','AllotmentApps.sname','AllotmentApps.cgpa')->join('Hostels','Hostels.id','Rooms.HostelID')->join('Groups','Groups.id','Rooms.ResidentID')->join('AllotmentApps','Groups.id','AllotmentApps.grpID')->orderBy('Groups.Group_CGPA', 'Desc')->get()->groupBy(
function($item) {
return $item->grpID;
}
) ->take($capasity);
// return $allot_apps;
return view('x', compact('allot_apps'));
}

Laravel Join query is not working for 4 tables

I have 4 tables
Table Name : Clinics
Fields: clinicID , clinicName
Table Name : locations
Fileds: locationID, clinicID,locationname
Table Name : Services
Fields: ServiceId , ServiceName
Table Name: LocationServices
Fields: locationServiceID, locationID , ServiceId
My requiremnt is that when i pass clinicID, i need to retrive Corresponding clinics service name, there may be more than one.
But when i tried join query is not working
Following is my code in controller
public function showClinic($id)
{
$clinic = Clinic::find($id);
$locations = Location::where('clinicID', $id)->get();
$locationsservices=\App\Clinic::with('locations');
var_dump($locationsservices);
die();
return view('clinic.show')->with(['locations' => $locations ,'clinic'=>$clinic]);
}
You can get this details by using relationships.
In the Clinic model,add
public function locations()
{
return $this->belongsTo('App\Models\Locations','clinicID','clinicID');
}
In the Locations model,add,
public function location_services()
{
return $this->hasOne('App\Models\LocationServices','locationID','locationID');
}
On the LocationServices model,
public function services()
{
return $this->hasOne('App\Models\Services','ServiceId','ServiceId');
}
You can get the result by,
$clinic_info = Clinic::find($id);
if(isset($clinic_info->locations))
{
if(isset($clinic_info->locations->location_services))
{
if(isset($clinic_info->locations->location_services->services))
{
echo $clinic_info->locations->location_services->services->ServiceName;
}
}
}
Reference Maybe HelpFull for You
Multi Joins
$data = DB::table('city')
->join('state', 'state.state_id', '=', 'city.state_id')
->join('country', 'country.country_id', '=', 'state.country_id')
->select('country.country_name', 'state.state_name', 'city.city_name')
->get();
return view('join_table', compact('data'));

How to get data from the foreign key in joined table in laravel 5.8

I want to get the details of products in the products table by calling it in the purchase_orders table in laravel5.8.
I try to use inner join but as its result its just values of numbers
$POs = DB::table('purchase_orders')
->join('products', 'purchase_orders.prod_id', '=', 'products.id')
->select('purchase_orders.id as id', 'products.name as name', 'products.cat_id as cat', 'products.size_id as size', 'products.price as price', 'purchase_orders.quant as quant', 'purchase_orders.total as total', 'purchase_orders.created_at as req_date')
->orderBy('purchase_orders.id','DESC')
->get();
Here are the 2 table and the result.
products table
purchase_orders
result
Create a relationship in PurchaseOrders Model:
public function products()
{
return $this->hasMany('App\Models\Product','id','prod_id');
}
You can call the result by:
$res = PurchaseOrder::find($id);
foreach($res->products as $product)
{
echo $product->name;
}
Using join:
$POs = DB::table('purchase_orders')
->join('products', 'purchase_orders.prod_id', '=', 'products.id')
->select('products.*','purchase_orders.id as purchase_id','purchase_orders.total','purchase_orders.status')
->orderBy('purchase_orders.id','DESC')
->get();
if you want categories table too, add another join function.
Try this for a relationship
public function products()
{
return $this->hasMany('App\Models\Product','prod_id','id');
}
public function products()
{
return $this->hasMany('App\Models\Product','prod_id','id');
}
To out put relationship data is like this
$variable->product->name
or
$variable->product['name']

Issue with group by laravel and sql

Firstly I have problem which count products which are sold every day. In sql I have query
select product_name, sum(quantity) as quantity from invoice_product
join invoices on invoices.id = invoice_product.invoice_id
join products on products.id = invoice_product.product_id
where invoices.issued_at = '2019-05-16'
and products.`made_by_us` = 1
group by product_name
It show me interesting for me information but I used product_name to make group by but I should use product_id - I need show name too but I don't know how to do it.
Secondly I want to use it in Laravel so maybe someone know which is it possible to do it in Eloquent?
Thank you in advance :)
I would go with withCount() combined with select(DB::raw()), like this:
$products = Product::withCount(['invoices as quantity' => function ($query) {
$query->select(DB::raw('sum(quantity)'));
}])->get();
Then, you can access each quantity sum like this:
$quantity = $products->first()->quantity;
You would need to update your model relationships to achieve that.
Models:
InvoiceProduct Model
class InvoiceProduct extends Model
{
protected $table = 'invoice_product';
protected $guarded = [
'id',
];
}
public function invoice()
{
return $this->belongsTo('App\Invoice'); // Assuming `Invoice` Model is directly in app folder
}
public function product()
{
return $this->belongsTo('App\Product'); // Assuming `Product` Model is directly in app folder
}
Controller:
$full_query = InvoiceProduct::whereHas('invoice', function ($query) {
return $query->where('issued_at', '2019-05-16');
})->whereHas('product', function ($query) {
return $query->where('made_by_us', 1);
});
$product_names = $full_query->get(['product_name']);
$total_quantities = $full_query->sum('quantity');

Laravel query builder join where

I've got this query:
$query = QueryBuilder::for(Advertisement::class)
->with('locations');
The locations method on Advertisement looks like this:
public function locations()
{
return $this->belongsToMany(Location::class, 'advertisement_locations', 'advertisement_id', 'location_id');
}
So a advertisements belongsToMany locations in between is a pivot table called advertisement_locations.
Now I would only get the advertisements between a given long and latitude that's on the locations table.
How could I do this?
Use this:
$query = Advertisement::whereHas('locations', function($query) {
$query->whereBetween('long', [$min, $max])
->whereBetween('latitude', [$min, $max]);
});

Categories