How to get today's all orders by restaurant in laravel? - mysql

I'm trying to get today's orders by a restaurant. Here is my table structure
restaurants
id - integer
name - string
categories
id - integer
restaurant_id- foreign
name - string
items
id - integer
category_id - foreign
name - string
orders
id - integer
amonut- double
order_items (pivot table)
id - integer
order_id - foreign
item_id - foreign
Here is my restaurant model
public function restaurant_categories() {
return $this->hasMany(Category::class, 'restaurant_id')->orderBy('created_at', 'DESC');
}
public function restaurant_items() {
return $this->hasManyThrough(Item::class, Category::class, 'restaurant_id', 'category_id')->with('category', 'item_assets')->orderBy('created_at', 'DESC');
}
Here is my Item model
public function orders(){
return $this->belongsToMany(Order::class,'order_items','item_id', 'order_id' )
->withPivot('quantity','price');
}
By this code, I get specific restaurant's all orders
$restaurant = Restaurant::with('restaurant_items')->find($id);
$orders = [];
foreach ($restaurant->restaurant_items as $item) {
$orders[] = $item->orders;
}
But now, How & where can I add where condition to get only today's order? and also if I want to get specific date's orders then what to do?L

For Laravel 5.6+ version, you can just have to add whereDate() condition
$restaurant = Restaurant::with('restaurant_items')
->whereDate('created_at', Carbon::today())->get();
Or you can also use whereRaw()
$restaurant = Restaurant::with('restaurant_items')
->whereRaw('Date(created_at) = CURDATE()')->get();

Related

I have Product and Category Many to Many Relation. I need to fetch Product where category_id(in pivot table) = [1,2,3,4]

I have Product and Category Many to Many Relation. I need to fetch Product where category_id(in pivot table) = [1,2,3,4]
in my Category Model
public function all_product($categories_ids): BelongsToMany
{
return $this->belongsToMany(Product::class)->wherePivotIn('category_id', $categories_ids);
}
and in controller
$categories_ids = [1,2,3,4];
$category = Category::where('slug_id', $request->input('slug_id'))->first();
$product = $category->all_product($categories_ids)->get();
return $product;
here I get only associated product with that $category. but I need all product whose category_id are $categories_ids = [1,2,3,4].
please help me to solve this query. thank you

Join 3 tables based on column values - Laravel

LEADS TABLE
id
title
owner_id
from_table
EMPLOYEE TABLE
id
first_name
last_name
role
ADMIN TABLE
id
first_name
last_name
role
$users = Leads::query();
return Datatables::make($users)
->editColumn('owner_id', function ($user) {
if($user->from_table == 'employee'){
$emp = Employee::where('id',$user->owner_id)->first();
return $emp->first_name.' '.$emp->last_name.' ('.$emp->role.')';
}
if($user->from_table == 'admin'){
$admin = Admin::where('id',$user->owner_id)->first();
return $admin->first_name.' '.$admin->last_name.' ('.$admin->role.')';
}
})
the above solutions is working fine but we are unable to search column wise induvidual searching in datatables.
what i want is join query something like:
if(leads.from_table == employee)
// fetch data from EMPLOYEE TABLE i.e. LEADS TABLE + EMPLOYEE TABLE
id
title
owner_id
from_table
first_name
last_name
role
if(leads.from_table == admin)
// fetch data from ADMIN TABLE i.e. LEADS TABLE + ADMIN TABLE
id
title
owner_id
from_table
first_name
last_name
role
I think you should change your database structure to use polymorphic relations, they fully comply with your needs - https://laravel.com/docs/5.8/eloquent-relationships#polymorphic-relationships
from_table column should contain the class name of the parent model.
Add in Leads model
public function fetchOwner()
{
return $this->morphTo();
}
Add In Employee Model
public function employee()
{
return $this->morphOne('App\Employee', 'fetchOwner');
}
Add In Admin Model
public function employee()
{
return $this->morphOne('App\Admin', 'fetchOwner');
}
$users = Leads::with('fetchOwner');
return Datatables::make($users)
->editColumn('owner_id', function ($user) {
return $user->fetchOwner->name;
})
thanks to all who tried to help..
I'm answering my own question as i found the answer after 9 days digging everywhere..
so here is the answer:
you may want to replace owner_code by owner_id in your business table.
so i changed the from_table to owner_type & owner_type now should contain the class name as value ex: changed admin to App\Admin & employee to App\Employee in Database
App\Admin.php
public function employee()
{
return $this->morphOne('App\Leads', 'owner');
}
App\Employee.php
public function employee()
{
return $this->morphOne('App\Leads', 'owner');
}
App\Leads.php
public function owner()
{
return $this->morphTo();
}
Thanks to: laravel morphTo how to use custom columns? (EddyTheDove) for pointing out the exact problem..

Compare two fields within different table using Laravel

I have two tables employees and customers , i've gave the schema below.
Customers('id' , 'username', 'location');
Employees('id' , 'EmployeeID' , 'CustomerID', 'location');
Currently I can use a query to retrieve customers details like the below query , note this is when the user is logged into the system hence the Auth::
$customerQuery1 = DB::table('customer')
->where('id', '!=', Auth::id())
->where('item', '=' , Auth::customer()->recommendation)
->get();
Each Employee has many customers ,I want other customers to see other customer items so i have attach the CustomerID field which is a foreign key and relates to the id field within the Customer table.
I've tried something like the below however I think I may need a join query but i'm unsure.
$query2 = DB::table('Customer','Employee')
->select('username')
->where(['EmployeeID' => Auth::id(), 'CustomerID' => 'id'])
->get();
$query2 = DB::table('Customer')
->select('username')
->join('Employee', 'Customer.id', '=', 'Employee.CustomerID')
->where(['EmployeeID' => Auth::id(), 'CustomerID' => 'id'])
->get();
I am then returning the values to my blade file like the below
return view ('pages.dashboard')
->with('query1',$query1)
and then Im using php indentation within my blade file to return the users data
#foreach ($query1 as $Userfound)
{{ $Userfound->username}}</p>
#endforeach
Actual Query needed in plain english
so I need to select a customer , where CustomerID == id
NOTE: id is from the customers table, CustomerID stored in the Employees table.
You can create Models using Laravel, for example:
Employee.php
public function customers()
{
return $this->hasMany('App\Customer');
}
Customer.php
public function employee()
{
return $this->belongsTo('App\Employee');
}
Which you can access like so:
$customer = Customer::where('id',Auth::user()->id)->firstOrFail();
or
$employee = Employee::where('id',Auth::user()->id)->firstOrFail();
And to see an employee's customers:
$employee->customers()->get();
Or to see the other customers of $customer's employer:
$customer->employee()->customers()->get();

LinQ to SQL adding delimited data but checking for duplicates

I have a table of Contacts, and a table of Groups which has a many-to-many relationship managed by a simple contacts_groups table:
contacts_groupsID Identity INT
ContactID INT
GroupID INT
I have a delimted String of contact IDs e.g. "1|23|987|2346|33|9821|" which I need to insert into the contacts_groups table (along with the groupID). I am using LinQ to SQL and C#, but want to know the most efficient way of looping through the delimited string (probably .Split()) checking for duplicates and inserting if not exist.
List<int> requested = contactIds.Split('|')
.Select(s => int.Parse(s))
.Distinct()
.ToList();
List<int> existing = (
from x in db.GroupsContacts
where x.GroupId == groupId
select x.ContactId
).ToList();
List<int> toBeAdded = requested.Except(existing).ToList();
foreach(int id in toBeAdded)
{
GroupsContacts record = new GroupsContacts();
record.GroupID = groupID;
record.ContactID = id;
db.InsertOnSubmit(record);
}
db.SubmitChanges();

Linq - Add Row to results for display only

I have a linq query that returns a brief order summary - product description and product price that gets bound to a data control. I want to add a row to be bound in this same control that displays tax information. The product description column would simply say "Tax" and the product price column would give a tax amount.
I used to retrieve a DataTable of these results and simply do a NewRow() and then set the datasource of my control as the DataTable. I'm looking for the equivalent technique when using LINQ to SQL. Thanks.
orderSummary.Union(taxRow)
In order to make it easy to add another "row" to the results of the LINQ query, you might want to consider creating a class to hold the results of the query. Then you could convert the results to a List, calculate the tax, and append the tax as an object of the class.
public class OrderSummary
{
public string Description { get; set; }
public decimal Amount { get; set; }
}
var taxRate = ...
var orderSummary = db.Orders.Where( o => o.ID == id )
.Select( o => new OrderSummary
{
Description = o.Product
.Details
.Description,
Amount = o.Qty * o.Product.Price
})
.ToList();
var tax = new OrderSummary
{
Description = "Tax",
Amount = orderSummary.Sum( o => o.Amount * taxRate );
};
orderSummary.Add( tax );
Then you can bind the list to your control using Description as the key and Amount as the value.