Laravel Eloquent, orderBy with relationship - php

I have an Project table which belongsTo a Client what I want to achieve is ordering the Project table by Clients name, how do I call the name of the client to the orderBy of the Project query?
$projects = Project::where('company_id', Auth::user()->company_id)
->search(trim($this->search))
->orderBy($this->column, $this->order)
->paginate($this->size);

You could do it with a subquery:
$projects = Project::where('company_id', Auth::user()->company_id)
->search(trim($this->search))
->orderBy(
Client::select('name')
->whereColumn('id', 'projects.client_id')
->limit(1)
)
->paginate($this->size);
If you also need the orderBy field to be conditional, you can wrap it in a when().
You can read more about Eloquent subqueries here: https://laravel-news.com/eloquent-subquery-enhancements

Related

How to Make Laravel Eloquent "AND" in a Query?

I am making a website in my job and I have an issue.
This is what I want to do; in MySQL (PHPMyAdmin) it works with no problems:
SELECT *
FROM tipo_usuarios
INNER JOIN users
ON tipo_usuarios.id = users.id AND
tipo_usuarios.jerarquia = "Administrador";
Well this is my Eloquent in Laravel, it works but only with IDs. I don't know how to add AND in Eloquent.
$visitas = User::join("visitas", "visitas.id_usuario", "=", "users.id")
->select("*")
->get();
You can use function for second argument in join
$visitas = User::join("visitas", function ($join) {
$join->on("visitas.id_usuario", "=", "users.id")
->on("visitas.jerarquia","=","Administrador")
})
->select("*")
->get();
However, you should read the documentation for creating Eloquent relationship. This is a more convenient and understandable functionality than using the query builder
Eloquent relationship

Laravel Eloquent OrderBy with a belongsTo on model Laravel

Is there anyway to dynamically OrderBy a belongsTo in Laravel? Or can this only work on join only? I would like to keep it as clean as possible that's why I use belongsTo.
This is my query, the problem I'm having is I don't know how to query the relational table.
$users = User::where('company_id', Auth::user()->company_id)
->search(trim($this->search))
->orderBy($this->column,$this->order)
->paginate($this->size);
My $columns variable
$columns = collect(['username'=>'Username',
'email'=>'Email'
]);
I want to add name, code, and id from the companies table to the options I have in the $columns variable.
This is gives me an error of column not found when I try to order by company.name
This is how I display it on the frontend because I have belongsTo in the modell
<td>{{$user->company->id}}</td>
<td>{{$user->company->name}}</td>
<td>{{$user->company->code}}</td>
<td>{{$user->username}}</td>
<td>{{$user->email}}</td>
I think you can use the joins, maybe try
$users = User::where('company_id', Auth::user()->company_id)
->leftJoin('company', 'company.id', '=', 'users.company_id')
->search(trim($this->search))
->orderBy($this->column,$this->order)
->paginate($this->size);
Now you have company.name in the querie to order by.

Query using Eloquent Laravel using "as"

How do you know the other code to get this query in laravel using eloquent?
$variable_value= DB::select(
'SELECT
sv.VARIABLE_NAME as sv_variable_name, sv.TYPE as sv_type, sv.ADDRESS as sv_address, sv.VALUE as sv_value,
ms.VARIABLE_NAME as ms_variable_name, ms.TYPE as ms_type, ms.ADDRESS as ms_address, ms.VALUE as ms_value
FROM MASTER_VARIABLES ms
JOIN SLAVE_VARIABLES sv ON ms.SLV_ADDRESS=sv.ID_VARIABLE'
);
Thank you for your help, guys!
It's all in the documentation. Give it a read?
# Selects
Specifying A Select Clause
You may not always want to select all columns from a database table. Using the select method, you can specify a custom select clause for the query:
$users = DB::table('users')->select('name', 'email as user_email')->get();
# Joins
Inner Join Clause
The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. You can even join to multiple tables in a single query:
$users = DB::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
$query = DB::table('MASTER_VARIABLES as ms')
->select(
'sv.VARIABLE_NAME as sv_variable_name',
'sv.TYPE as sv_type',
'sv.ADDRESS as sv_address',
'sv.VALUE as sv_value',
'ms.VARIABLE_NAME as ms_variable_name',
'ms.TYPE as ms_type',
'ms.ADDRESS as ms_address',
'ms.VALUE as ms_value'
)
->join('SLAVE_VARIABLES as sv', 'ms.SLV_ADDRESS', '=', 'sv.ID_VARIABLE')
->get();

How to get a collection of models using where and relationships?

I have an Order table with some relationships (Status, User) using their IDs to create it (status_id, user_id)
I need to get a collection of Order models using and Eloquent ORM but I need to filter by their status name (which is in Status table only) and user name (which is in User table only)
When I use 'join' in my query builder. The relationships aren't hydrating, like in this case:
$emprestimo = DB::table('emprestimos')
->join('status', 'status_id', '=', 'status.id')
->where('status.nome', 'Solicitado')
->where('emprestimos.dono_id', Auth::user()->id)
->get();
How can I filter using joins and also hydrate my collection of models?
you can try something like this
see if that works
$emprestimo = DB::table('emprestimos')
->join('status', function ($join) {
$join->on('emprestimos.status_id', '=', 'status.id')
->where('status.nome', 'Solicitado')
})
->where('emprestimos.dono_id', Auth::user()->id)
->get();

Laravel Query Builder - sum() method issue

I'm new to laravel and I have some issues with the query builder.
The query I would like to build is this one:
SELECT SUM(transactions.amount)
FROM transactions
JOIN categories
ON transactions.category_id == categories.id
WHERE categories.kind == "1"
I tried building this but it isn't working and I can't figure out where I am wrong.
$purchases = DB::table('transactions')->sum('transactions.amount')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->select('transactions.amount')
->get();
I would like to get all the transactions that have the attribute "kind" equal to 1 and save it in a variable.
Here's the db structure:
transactions(id, name, amount, category_id)
categories(id, name, kind)
You don't need to use select() or get() when using the aggregate method as sum:
$purchases = DB::table('transactions')
->join('categories', 'transactions.category_id', '=', 'categories.id')
->where('categories.kind', '=', 1)
->sum('transactions.amount');
Read more: http://laravel.com/docs/5.0/queries#aggregates
If one needs to select SUM of a column along with a normal selection of other columns, you can sum select that column using DB::raw method:
DB::table('table_name')
->select('column_str_1', 'column_str_2', DB::raw('SUM(column_int_1) AS sum_of_1'))
->get();
You can get some of any column in Laravel query builder/Eloquent as below.
$data=Model::where('user_id','=',$id)->sum('movement');
return $data;
You may add any condition to your record.
Thanks
MyModel::where('user_id', $_some_id)->sum('amount')

Categories