Join in Pivot tabel Laravel - php

I have following tables:
Food:
Foodid(pk)
FoodName
FoodImage
Description
Categories:
Category_id(pk)
CategoryName
Restaurant
Res_id(pk)
ResName
Address
category_food_restaurant
Category_id(fk)
Food_id(fk)
Res_id(fk)
Now I want to show Food items based on category name.For that I make query as:
$Category = DB::table('Food')
->select('Food.Food_id','Food.FoodName',
'Food.FoodImage','Categories.CategoryName')
->join('Categories','Categories.Category_id',
'=','category_food_restauarant.Category_id')
->where('Categories.CategoryName',
'=','Breakfast')->get();
But this gives me error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Food.Category_id' in 'on clause' (SQL: select Food.Food_id, Food.FoodName, Food.FoodImage, Categories.CategoryName from Food inner join Categories on Categories.Category_id = Food.Category_id where Categories.CategoryName = Breakfast).
Where is the problem.How I can show food items based on category by using these tables?

You are joining Food table and Categories table but there is no relation between them directly. So you have to join these two tables through category_food_restaurant. The following should work:
DB::table('category_food_restaurant')
->select('Food.Food_id','Food.FoodName',
'Food.FoodImage','Categories.CategoryName')
->join('Categories','Categories.Category_id',
'=','category_food_restaurant.Category_id')
->join('Food','Food.Food_id',
'=','category_food_restaurant.Food_id')
->where('Categories.CategoryName',
'=','Breakfast')->get();

Related

How to aggregate query on related table's field in Laravel?

I have a One To Many (Inverse) relation on my laravel 5.4 application. There are two models Sale and Vehicle which are related and associated with the scene.
The relation on the Sale model is :
public function vehicle()
{
return $this->belongsTo('App\Models\Vehicle','vehicle_id');
}
Table sales has following fields :
id, vehicle_id, date_time, status etc.
Table vehicles has following fields :
id, reg_number, volume, status etc.
What I want is, sum of the field 'vehicles.volume' of Sale records within the search conditions.
I have tried some methods like the following one:
$query = Sale::where('status', 1);
$query = $query->where('date_time', '<', "2017-05-10 10:10:05");
$totalVolume = $query->whereHas('vehicle')->sum('vehicles.volume');
and it resulted in the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'vehicles.volume' in 'field list' (SQL: select
sum(vehicles.volume) as aggregate from sales where status = 1
and date_time < "2017-05-10 10:10:05" and exists (select * from vehicles where sales.vehicle_id =
vehicles.id))
hopefully waiting for a solution to 'get the sum of the volume of the sales' using eloquent query.
Edited
You need to use a join before summing the vehicles.volume column
$totalVolume = Sale::where('status', 1)
->where('date_time', '<', "2017-05-10 10:10:05")
->join('vehicles', 'vehicles.id', '=', 'sales.vehicle_id')
->select(DB::raw('sum(vehicles.volume) as total_volume');
select sum(volume) as aggregate from vehicles INNER JOIN sales ON vehicles.id=sales.vehicle_id

mysql join same table with another table

I have a table name tbl_user
This table contain a column name db_responsibleid contain the id of the responsible of this person and this person is in this table also
example mohammad have db_uid=1 and samir have db_responsibleid=1 this mean that mohammad is responsible for samir
also i have another table name tbl_department the table user contain the id of the department on the column name db_udepartment
I try to have the name of the department and the name and the last name of the responsible where db_uid='$id'
$id will be getting from url
this is the query that i use
SELECT
user.db_uid,
user.db_fname,
user.db_lname,
user.db_username,
user.db_pass,
user.db_email,
user.db_phone,
user.db_jobtitle,
user.db_level,
user.db_isemployee,
user.db_responsibleid,
user.db_companyname,
user.db_udepartment,
tbl_department.db_department,
tbl_department.db_did,
parent.db_responsibleid,
parent.db_fname as pfname,
parent.db_lname as plname,
parent.db_uid
from tbl_user as user,tbl_department
join tbl_user as parent
on
user.db_responsibleid=parent.db_uid
where
user.db_udepartment=tbl_department.db_did
and
user.db_uid='$id'
But this query give me this error Unknown column 'user.db_responsibleid' in 'on clause'
How can i solve this problem and get all information with the name of the responsible and the name of the department ??
You can not mix implizit and explizit join.
If you decided to use join you have to do it everywhere:
from tbl_user as user
join tbl_department on user.db_udepartment=tbl_department.db_did
join tbl_user as parent
on
user.db_responsibleid=parent.db_uid
where
user.db_uid='$id'
Hint: use prepared Statements to prevent SQL-injection

Join in 3 tables

I have 3 tables food,restaurant and categories.
I want to make join between these. I have a query to join food and categories as:
> $Category = DB::table('food')->select('food.Food_id','food.FoodName','food.FoodImage','food.FoodType','categories.CategoryName')->join('categories','categories.Category_id','=','food.Category_id')->where('categories.CategoryName', '=','Breakfast')->get();
I want to join restaurant with this. How I can do that?
My tables are:
food:
Food_id(PK)
FoodName
Category_id(FK)
And category table is:
Category_id(PK)
CategoryName
And restaurant table is:
Res_id
Res_Name
Address_loc
Food_id(FK)
$Category = DB::table('food')->select('food.Food_id','food.FoodName','food.FoodImage','food.FoodType','categories.CategoryName', 'restaurant.Res_Name')
->join('restaurant', 'restaurant.Food_id', '=', 'food.Food_id')
->join('categories','categories.Category_id','=','food.Category_id')
->where('categories.CategoryName', '=','Breakfast')->get();
You can use Food_id to join the restaurant onto food.
(Not sure if the syntax of the code is correct, but it fits to your example. Might have to change the tablename of restaurant as you seem to be switching between lower and upper case)

Unknown column 't.faic' in 'field list'

When I execute my query i got an error
[Err] 1054 - Unknown column 't.faid' in 'field list'
I have a table called
app_interview with fields 'atid','atic','atname','inttotal'
applicants with the same atic are just one person.
I want to total all the total of applicant with same atic field value and divide it with 7 and save the average score to a new table called:
afnup_worksheet with field 'faid','faic','fnl_name','ftotal'
heres my current query:
INSERT INTO afnup_worksheet (faid,faic,fnl_name,ftotal)
SELECT DISTINCT
t.faid
,t.faic
,t.fnl_name
,(SELECT SUM(t2.inttotal) FROM app_interview t2 WHERE t2.atic = t.faic)/7 thissum
FROM app_interview t
GROUP BY atname HAVING COUNT(DISTINCT atic)=1
You.re selecting t.faic, where t refers to app_interview, but according to the details you have posted, app_interview doesn't conatin a field called faic. This is also true for t.faid and t.fnl_name.
According to your description, app_interview does not have a faid column

Displaying alternate column when using foreign keys

I have an issue regarding PHP, MySql and foreign keys. I understand foreign keys and have a relationship between two tables in place as described:
Let's say I have 2 tables: 'vehicles' and 'manufacturers'.
Each row in the 'vehicles' table includes a manufacturerId column which is a foreign key relating to the 'manufacturers' table. This is set up nicely, in PhpMyAdmin when I insert a new row into the 'vehicles' table the manufacturerId column has a drop-down menu with the manufacturerId's listed as options. Very nice.
BUT: In my application, of course, I don't want the user to have to know (or have to guess) what the correct number for 'Ford' or 'BMW' is when they add a new vehicle, I want them to be able to choose the manufacturer by name.
But how does the application know the manufacturer names based on the manufacturerId? How does the application know there is a relationship between the 2 tables? Am I supposed to hard-code the relationship in the application? Am I supposed to modify all my queries to have a JOIN between the 2 tables? Or hard-code a query to get a list of manufacturers every time I want to display a drop-down of manufacturers?
Is there a way for the application to know about relationships between tables and be able to display data from a text column instead of the int column used as the ID?
Assuming your 2 table are structured like this:
VEHICLES
id
manufacturerId
vehicleName
MANUFACTURERS
id
manufacturerName
You would create your vehicle manufacturer select menu for users by querying the database like this:
// query the database
$q = 'SELECT id, manufacturerName FROM manufacturers';
$r = mysqli_query($link, $q);
// display a select menu using id and manufacturerName
echo '<select name="manufacturer">';
while($row = mysqli_fetch_assoc($r)) {
echo '<option value="'.$row['id'].'">'.$row['manufacturerName'].'</option>';
}
echo '</select>';
To use the post data from that menu to add a vehicle & manufacturer id to your vehicles table:
$q = "INSERT INTO vehicles (manufacturerId, vehicleName) VALUES ({$_POST['manufacturer']}, '{$_POST['vehicleName']}')";
mysqli_query($link, $q);
Finally, if you wish to select the vehicle name and manufacturer in the same query, you would join the tables like this:
// Select vehicle name and manufacturer for vehicle with id of 1
$q = "SELECT v.vehicleName, m.manufacturerName, v.id AS vehicleId, m.id AS manufacturerId
FROM vehicles AS v, manufacturers AS m
WHERE v.manufacturerID = m.id
AND v.id = 1";
mysqli_query($link, $q);
I think that should answer all your questions in one way or another!

Categories