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.
Related
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
I'm trying to get all the data from the parent that only has a child. Please see my code below.
$customers = Customer::with(['items' => function($query){
return $query->where('status', 2);
}])->get();
dd($customers);
But the code above returns all the customer. By the way, I'm using laravel 4.2.
Items Table:
Customer Table:
with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.
has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.
e.g :
$users = Customer::has('items')->get();
// only Customer that have at least one item are contained in the collection
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
e.g
$users = Customer::whereHas('items', function($q){
$q->where('status', 2);
})->get();
// only customer that have item status 2
Adding group by to calculating sum
this is another example from my code :
Customer::select(['customer.name', DB::raw('sum(sale.amount_to_pay) AS total_amount'), 'customer.id'])
->where('customer.store_id', User::storeId())
->join('sale', 'sale.customer_id', '=', 'customer.id')
->groupBy('customer.id', 'customer.name')
->orderBy('total_amount', 'desc')
->take($i)
->get()
in your case :
Customer::select(['customer_id', DB::raw('sum(quantity) AS total')])
->whereHas('items', function ($q) {
$q->where('status', 2);
})
->groupBy('customer_id')
->get();
whereHas() allow you to filter data or query for the related model in your case
those customer that have items and it status is 2
afetr getting data we are perform ->groupBy('customer_id')
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns.
select(['customer_id', DB::raw('sum(quantity) AS total')]) this will select customer id and calculate the sum of quantity column
You should use whereHas not with to check child existence.
$customers = Customer::whereHas('items', function($query){
return $query->where('status', 2);
})->get();
dd($customers);
I assume you already defined proper relationship between Customer and Item.
You should try this:
$customers = Customer::whereHas('items', function($query){
$query->where('status', 2);
})->get();
dd($customers);
Customer::select(['items.customer_id',DB::raw('count(items.id) AS total_qty')])
->join('items', 'items.user_id', '=', 'customer.customer_id')
->groupBy('items.customer_id')
->havingRaw('total_qty > 2')
->get();
OR
$data=DB::select("select `items`.`customer_id`, count(items.id) AS total_qty
from `customers`
inner join `items`
on `items`.`customer_id` = `customers`.`customer_id`
group by `items`.`customer_id` having total_qty >= 2");
correct table name and column name.
This is the query I currently using for Inner Join in my laravel app:
public function getReservationListAPI()
{
$id = JWTAuth::parseToken()->authenticate()->id;
$result = DB::table('pporders AS ord')
->join('products AS pd', 'ord.product_id', '=', 'pd.id')
->select('ord.*')
->where('pd.user_id',$id)
->get();
dd($result);
}
How can I wrote this query in Eloquent form? Thanks!!
EDIT
Relationship:
Product hasMany Order
Order belongsTo Product
User hasMany Product
Product belongsTo User
It depends on your relation, but something like this:
Pporders::with(['product' => function($q) use($id) {
$q->where('user_id', $id);
}])->get();
But it won't make the same sql query what you described, but gives the same result.
I'm working with L5 and elequent
My table structure is..
users
id
other field
auctions
id
other field
lots
id
auction_id
other field
lot_user
lot_id
user_id
I want to find auctions for a user.
How can i do this?
$user = User::find($id);
$auctions = $user->auctions();
I have got an idea to do this with eloquent..
$auctions = $user->lots()
->join('auctions','auctions.id','=','lots.id')
->select(['auctions.*'])
->get();
I'm not sure Eloquent is going to be very efficient here, but you could do something like :
In your User(s) class, you need to define a many-many relationship like :
public function lots()
{
return $this->belongsToMany('App\Lot');
}
In your Lot(s) class, you need to define the inverse of a one-to-many relationship like:
public function auctions()
{
return $this->belongsTo('App\Auction')
}
Then, to get Lots for a user, you'd do something like :
$user->lots();
To get auctions, you'd need to loop over lots and call $lot->auctions() for each one, and then filter by id to get the unique auctions.
This is a case where it would probably be easier to use the DB facade to built a query instead of just trying to use Eloquent.
About DB facade.
Raw query will looks like this:
SELECT * FROM auctions AS a
INNER JOIN lots AS l ON (l.auction_id = a.id)
INNER JOIN lot_user AS lu ON (lu.lot_id = l.id AND lu.user_id = $findUserId)
GROUP BY a.id
And using query-builder you can do it like this:
DB::table('auctions')
->join('lots', 'lots.auction_id', '=', 'auctions.id')
->join('lot_user', function ($join) {
$join->on('lot_user.lot_id', '=', 'lots.id')
->where('lot_user.user_id', '=', $findUserId);
})
->groupBy('auctions.id')
->get();
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();