I have the following tables:
Dishes
id
name
Customers
id
name
Ingredients
id
name
Dishes_Ingredients (table to put in relation dishes and ingredients)
id
dish_id
ingredient_id
Customers_Allergic_Ingredients (customers are allergic to certain ingredients)
id
customer_id
ingredient_id
Customers_Intolerance_Ingredients (customers are intolerant to certain ingredients)
id
customer_id
ingredient_id
I need to get the following information from the database: for a given customer_id, I want to retrieve all the dishes which the customer is not allergic to and not intolerant to, using Laravel Query Builder.
This is what I tried so far:
$dishes = DB::table('dishes')
->join('dishes_ingredients', 'dishes.id', '=', 'dishes_ingredients.dish_id')
->join('customers_allergic_ingredients', 'dishes_ingredients.ingredient_id', '<>', 'customers_allergic_ingredients.ingredient_id')
->join('customers_intolerance_ingredients', 'dishes_ingredients.ingredient_id', '<>', 'customers_intolerance_ingredients.ingredient_id')
->where('customers.id', 1)
->select('dishes.id', 'dish_translations.name')
->get();
Try to use Laravel Eloquent: Relationships
this will save your time & your code will be more simply....
https://laravel.com/docs/5.2/eloquent-relationships
I don't know Laravel but if you just want to solve your problem:
SELECT *
FROM Dishes d
WHERE d.id NOT IN
(
SELECT DISTINCT dish_id
FROM Dishes_Ingridients
WHERE ingredient_id IN
(SELECT DISTINCT ingredient_id FROM Customers_Allergic_Ingredients cai WHERE cai.customer_id = ?)
OR
ingredient_id IN
(SELECT DISTINCT ingredient_id FROM Customers_Intolerance_Ingredients cii WHERE cii.customer_id = ?)
)
$dishes = DB::table("dishes AS a")
->select(array("a.*" ))
->join("dishes_ingredients AS b", "a.id", "b.dish_id")
->join("Customers_Allergic_Ingredients AS c", "b.id", "=", "c.ingredient_id")
->where("c.customer_id", "!=", $customer_id)
->groupBy("a.id")
->get();
This will give you all dishes made with ingredients that the customer is not allergic to
Related
I'm creating simple PHP / Laravel app and I have reached a problem:
I need to somehow join 2 queries, but I am not sure how to.
I could do it with some messy PHP loops, but I know that's not the right approach.
my queries in Laravel's code looks:
$cars = Car::get();
$drives = Drive::select(DB::raw('car_id, max(odometer) as odometer'))->groupBy('car_id')->get();
in plain SQL something like:
$cars = 'SELECT * FROM cars';
$drives = 'SELECT car_id, max(odometer) as odometer FROM drive GROUP BY car_id';
(drive)'car_id' = (cars)'id'
Update: Forgot to mention: I have 'odometer' field in 'car' and get max('odometer') from drives, so if there is something returned from 'drives' it should overwrite the one returned from 'car'
DRIVE:
id
car_id
user_id
odometer
liters_filled
route
is_private
is_refill
is_full
checque
date
deleted_at
created_at
updated_at
CARS:
id
title
plate_number
year
tank_size
odometer
user_id
deleted_at
created_at
updated_at
Thank you for your time and help!
To be honest I'm not 100% on what you are asking but you could try the following:
SELECT cr.id ,
dr.oodometer
FROM Car cr
INNER JOIN (SELECT dr.car_id,MAX(dr.oodometer) AS oodometer
FROM Drive dr
GROUP BY car_id ) dr ON dr.car_id = cr.id
SELECT cars.*, max(driver.oodometer) as odometer FROM cars
INNER JOIN driver on cars.id=driver.car_id
group by driver.car_id
This query will join the 2 tables for you and get you the info. The table names i used are your variable names for the sake of the example.
Edit for Laravel:
In config/database.php at mysql change :
'strict' => true,
to false.
I wonder if its possible to select two tables and join a third table
I have 3 tables:
upvotes
-id (PK)
-voteOn (FK) - points to users PK
-voteBy (FK) - points to users PK
-vote (Int)
-voteAdded (Int) - unix timestamp
downvotes
-id (PK)
-voteOn (FK) - points to users PK
-voteBy (FK) - points to users PK
-vote (tinyInteger)
-voteAdded (Int) - unix timestamp
users
id (PK)
username
What I now want to do is ~ select ALL votes from the tables upvotes and downvotes where voteOn = 2 then join table users on voteBy orderBy voteAdded Asc
More or less I want to get all votes on a specific user then join the users table so that I can get the username of the person who placed the vote
U can use the DB facade to achieve this which will generate an sql query that is fired on the db
$users = DB::table("users AS a")
->select(array("a.id as user_id", "a.username", "b.voteOn as upvote_on",
"b.vote as upvote", "b.voteAdded as upvote_added","c.voteOn as downvote_on", "c.vote as downvote",
"c.voteAdded as downvote_added"))
->join("upvotes AS b", "a.id", "=", "b.voteBy")
->join("downvotes AS c", "a.id", "=", "c.voteBy")
->orderBy("b.voteAdded", "asc")
->get();
Then you can loop through the users using foreach
foreach($users as $user) {
$user->user_id;
//use the alias as used in the select chained function
}
That should work
I'm creating a ranking of players badges and I'm stuck with db query.
Tables:
user(id), club(id), club_user(user_id, club_id), badges(user_id)
I would like to get list of all users from specified club (for example club.id = 1) with amount of badges they have. Results should be ordered by number of badges.
How to create that kind of db query? Is it possible with Eloquent?
Should it be made with db::table and join?
Table user
id|name
1|John
2|Robert
3|Kate
Table club
id|name
1|Sunshine Club
2|Example Club
Table club_user
user_id|club_id
1|1
2|1
3|2
Table bagdes
id|name|user_id|club_id
1|Champion|1|1
2|Some badge|1|1
3|example|2|1
4|Gold Badge|3|2
so if I would like to get ranking of users from club 1, ordered by badge count.
I should get:
name|number of badges
John|2 (badges)
Robert|1 (badge)
Kate is not it this club.
Try this
select user.name ,user.id as userid , (select count(bagdes.id) from
bagdes where user_id= userid)
as total_badges from user inner join club_user on
user.id = club_user.user_id where club_user.club_id = 1
You will get your output.
Finally I made it with this DB::table query:
$users = DB::table('users')
->select('users.name', DB::raw('count(*) as badges'))
->join('badges', 'badges.user_id', '=', 'users.id')
->where('badges.club_id', 1)
->groupby('users.id')
->orderBy('badges', 'DESC')
->get();
I'm new on Laravel & Eloquent. I have Users, Products and Votes tables on my DB. Users can vote (0 to 5) on products, so it is a "many to many" relationship, with the Votes table acting like a pivot:
Users: id, name, email, password
Products: id, name, model, brand
Votes: user_id, product_id, vote
I mapped this schema like this:
// User model:
public function product_votes()
{
return $this->belongsToMany('App\Product', 'votes')->withPivot('vote');
}
// Product model:
public function product_votes()
{
return $this->belongsToMany('App\User', 'votes')->withPivot('vote');
}
So John can vote 5 on product X and 0 on product Y. Bob can vote 2 on product X, 3 on product Y, and so on...
I'm trying to query all products, with the sum of votes of each one of them. Something like:
SELECT p.*, (SUM(v.vote) / COUNT(*)) as votes FROM products p INNER JOIN votes v on v.product_id = p.id GROUP BY p.id
How can I do that with QueryBuilder? My mapping is right?
The following will do the trick:
Product::select('products.*', DB::raw('SUM(vote)/COUNT(*) as votes'))
->join('votes', 'votes.product_id', '=', 'products.id')
->groupBy('products.id')
->get();
You can see the query that will be run by calling toSql() instead of get().
I'm stuck with creating a where query. I have table item with item_id, item_title, item_description, item_created, item_approved. I also have a table article with PK item_id (from item table) and article_body. The last table is media with medium_id, item_id (FK), medium_url and medium_type.
Now I would like to select all the data from media where item.item_approved is not NULL and where item.item_id ins't present in the article table.
Now I can select all the data from media where item.item_approved is not NULL. But now I need to do another check that he doesn't select the items that are also in article table. My query so far:
$repository = $entityManager->getRepository('VolleyScoutBundle:Media');
$query = $repository->createQueryBuilder('m')
->join('m.item', 'i')
->where('i.itemApproved is not NULL')
->getQuery();
Most likely that you must use 2 queries. With JOINs it can not be done.