how to order by column of related table in laravel eloquent? - php

I have two table and their models named Attendance and Line,
I am trying to get all from 'attendances' which is group by line_id and order by line names
here is a portion of what I have tried
public function lineWiseReport(Attendance $attendance){
$repository = $this->repository;
if(Input::has('date')){
$date = Input::get('date');
$attn->where('date','like','%'.$date.'%');
$attendances = $attn
->where('employee_type_id',2)
->orderBy('lines.name', 'ASC') //how to do this?
->get()->groupBy('line_id');
}else{
$date = '';
$attendances = [];
}
}
class Attendance extends Model
{
public function line()
{
return $this->belongsTo(Line::class);
}
}
Now I get only group by line_id but I want it to be sorted like Line A, Line B, Line C in a ascending order.

You have to join with the lines table before you can use values from that table.
$attendances = $attn
->join('lines', 'lines.id', '=', 'line_id')
->where('employee_type_id', 2)
->orderBy('lines.name', 'ASC') //how to do this?
->get()
->groupBy('line_id');
This might however return more records if a model contains more lines.

Related

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');

i get this error: Object of class Illuminate\Database\Eloquent\Builder could not be converted to string in laravel ORM

I get this error:
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
when I run this code:
public function index()
{
save_resource_url();
//$items = News::with(['category', 'photos'])->get();
$items = Solicitud::rightjoin(News::with(['category', 'photos']),'news.id','=','solicitud.event_id')->count('*','event_id','as','total')->get();
return $this->view('news_events.index', compact('items'));
}
my original sql query
SELECT *,count(event_id) as total FROM solicitud RIGHT JOIN news ON news.id = solicitud.event_id group by title;
The error you are getting is because you are putting the Builder as first parameter News::with(['category', 'photos']). it should only be the string(table name) like 'news'.
Click here to read more
So the query should
$items = Solicitud::rightjoin( 'news','news.id','=','solicitud.event_id')->count('*','event_id','as','total')->get();
Solve:
my original code
public function index()
{
save_resource_url();
$items = News::with(['category', 'photos'])->get();
return $this->view('news_events.index', compact('items'));
}
change my sql query:
SELECT *,count(event_id) as total FROM solicitud RIGHT JOIN news ON news.id = solicitud.event_id group by title;
this query produced duplicate columns
for this:
select news.*,count(event_id) as total from news left join solicitud on solicitud.event_id = news.id group by news.id;
this query shows only the columns of the users table plus the 'total' table in relation to the 'request' table
in my code transform to eloquent
public function index()
{
save_resource_url();
$items = News::with(['category', 'photos'])->leftjoin('solicitud','solicitud.event_id','=','news.id')->groupBy('news.id')->select('news.*',DB::raw('count(event_id) as total'))->get();
return $this->view('news_events.index', compact('items'));
}

Laravel table joins

I'm trying to do some table joins and having some trouble.i need to display
the customer’s complete name and title, item description, quantity ordered, for each item ordered after April 2000. i made a SQL script that works but i need to use Laravel ORM.
SELECT `first_name`,`last_name`,o.order_id,`quantity`,`description`,`date_placed`
FROM `customer` c
JOIN `order` o
ON c.`customer_id` = o. `customer_id`
JOIN `orderline` ol
ON o.`order_id` = ol. `order_id`
JOIN `item` i
ON ol.`item_id` = i. `item_id`
WHERE `date_placed` > '2000-4-00';
I created 2 models for the tables "Customer", "Order"
here is my Customer model
public function orders(){
return $this->hasMany('App\Order','customer_id');
}
here is my order model
public function orderline(){
return $this->hasMany('App\Orderline','order_id');
}
right now i am able to get some of my data but i dont feel like this is a good way to go about
$customer = Customer::all();
foreach($customer as $input){
$item = Customer::find($input->customer_id)->orders;
$name = $input->title . ' ' . $input->first_name . ' ' . $input->last_name;
$datePlaced = null;
$orderID = null;
foreach($item as $value){
$orderID = $value->order_id;
$datePlaced = $value->date_placed;
$order = Order::find($value->order_id)->orderline;
}
if anyone could point me in the right direction that would be great.
It looks like you want to get all Customers with their Orders and OrderLines?
Customer::with(['order' => function ($query) {
$query->where('date_placed', '>=', '2000-04-01')->with('orderline');
}])->get();
If you want to limit the columns on the relationships, you can...
Customer::with(['order' => function ($query) {
$query->select(/* columns */)->where('date_placed', '>=', '2000-04-01')
->with(['orderline' => function ($query) {
$query->select(/* columns here */);
}]);
}])->get();
Just make sure if you specify the columns in the relationships, that you're selecting all of the foreign keys or related columns for each relationship.

Cannot get relation in Laravel pivot tables

I want to build relations between three tables in laravel. Currently i have three models
Classroom,
public function subjects(){
return $this->belongstoMany('Subject','subject_section_classroom');
}
Section,
Subject
My Tables are
classrooms(id, name)
sections(id, name)
subjects(id, name)
subject_section_classroom( id, classroom_id, section_id, subject_id)
In my classroomsController I have
public function assignsubjects($class_id, $section_id){
$classroom = Classroom::find($class_id);
$section = Section::find($section_id);
$subjects = Subject::lists('name','id');
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1);
$subjects = Subject::lists('name','id');
return view('assignedit', compact('classroom','section','subjects', 'selected_subjects'));
}
But I can't get the selected_subjects from above relation. And when I tried to get the sql of the above query (with ->toSQL()), I get
`"select * from `myschool_subjects` inner join `myschool_subject_section_classroom` on `myschool_subjects`.`id` = `myschool_subject_section_classroom`.`subject_id` where `myschool_subject_section_classroom`.`classroom_id` = ? and `section_id` = ?"`
I can't figure what I am doing wrong here.
Please Help.
I think your problem is coming from
php
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1);
Change it to:
php
$selected_subjects = $classroom->subjects()->where('section_id', '=', 1)->get();

Selecting a single column from model to controller in codeigniter3.0.0

I am new in codeigniter.
I need only the available column from the model than what code I write in the controller to get a single column
My model code is:
public function check_reservation($restaurant_id,$date,$people,$start_time,$end_time){
$sql="SELECT
r.restaurant_id,r.restaurant_name,r.capacity,rs.start_time,rs.end_time,rs.people,rs.date,r.capacity - SUM(IFNULL(rs.people,0)) AS available FROM restaurant r
LEFT JOIN reservation rs ON r.restaurant_id = rs.restaurant_id
AND ".$date." = rs.`date`
AND ".$people." = rs.`people`
AND '".$start_time."' = rs.`start_time`
AND '".$end_time."' = rs.`end_time`
WHERE r.restaurant_id = ".$restaurant_id."
GROUP BY r.`restaurant_id`";
$query=$this->db->query($sql);
return $query->result();
}
Thank you
It's not clear what you need. If you want to get only one column in the Controller, when you iterate with foreach (or for), you ask for your column name.
foreach ( $records as $record ) {
echo $record['restaurant_name'];
echo "<br/>";
}

Categories