I wanna question about how to use order by inside eager load laravel eloquent, I already have a query like this :
$getData = StockIn::select(
StockIn::raw('group_concat(stock_ins.id_stock_in) as id_stock_ins'),
'stock_in_id_type'
)
->with(['type_of_items' => function ($query) {
$query->orderBy('type_of_item');
}])
->orderBy('type_of_items.type_of_item')
->groupBy('stock_ins.stock_in_id_type')
->get();
But when I compile the query and look to the result, the result of my query didn't make result with order by query, Am I making a mistake in my query so that the result is matching with my expectation? Thanks before
Here for my model :
Stock In :
public function type_of_items() {
return $this->belongsTo('App\TypeOfitem', 'stock_in_id_type');
}
Type Of Item :
public function stock_ins() {
return $this->hasMany('App\StockIn');
}
when I try to look on the console, the result of my query like this :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'type_of_items.type_of_item' in 'order clause' (SQL: select group_concat(stock_ins.id_stock_in) as id_stock_ins, `stock_in_id_type` from `stock_ins` group by `stock_ins`.`stock_in_id_type` order by `type_of_items`.`type_of_item` asc)
You're currently using order by on eager loaded data.
Instead, you need to call it on the model itself.
$getData = StockIn::select(
StockIn::raw('group_concat(stock_ins.id_stock_in) as id_stock_ins'),
'stock_in_id_type'
)
->with(['type_of_items' => function ($query) {
$query->orderBy('type_of_item');
}])
->orderBy('type_of_items.type_of_item')
->groupBy('stock_ins.stock_in_id_type')
->get();
You can also try it out without groupBy first, to be sure you're getting the correct results
Related
I'm using Laravel 9 to perform a withSum on my relationship credit_transactions. I need to return all PersonalAccessToken models where the credit_balance is less than a certain value, for example, 50 - this way my application knows whether to top up their balance.
This is my query:
/**
* Get all keys that can be auto topped-up
*/
public function getEnabledTopUpKeys()
{
return PersonalAccessToken::whereNotNull('region_code')
->where('auto_topup_enabled', true)
->whereNotNull('auto_topup_slug')
->withSum('credit_transactions AS credit_balance', 'delta')
->where('credit_balance', '<', 100)
->get();
}
This doesn't work, it throws an error:
Unknown column 'credit_balance' in 'where clause'
What am I missing to perform this?
withSum generates a sub query, so it can't be used in a where query. But that sub query creates an on-the-fly column that you can add to your query. For instance,
Order::withSum('orderItems', 'quantity')
->take(5)
->get();
creates an aliased column named order_items_sum_quantity, that I can then use as a having query:
Order::withSum('orderItems', 'quantity')
->having('order_items_sum_quantity', '>', 100)
->take(5)->get();
In your case, you may be getting a column named credit_balance_sum_delta that you can use in your query:
PersonalAccessToken::whereNotNull('region_code')
->where('auto_topup_enabled', true)
->whereNotNull('auto_topup_slug')
->withSum('credit_transactions AS credit_balance', 'delta')
->having('credit_balance_sum_delta', '<', 100)
->get();
If that isn't quite the correct column name, try getting one record without the having line, then check the results to find out the column name
I'm trying to return two columns ('question' and 'reponse') from two different table (also named 'question' and 'reponse') using a createQueryBuilder. I have no problem when I return one column, but it doesn't work when I try adding a new Select option.
My Controller that render my view and the data correctly :
public function play(Request $request) {
$id = $request->query->get('id');
$cat = $this->repository->findIdQuestion($id);
return $this->render('quiz_select.html.twig', [
'question' => $cat
]);
Here is my Question Repository that works when I remove the 'addSelect'
What can I do ?
public function findIdQuestion($id) {
return $this->createQueryBuilder('question')
->addSelect('reponse')
->from('App\Entity\Reponse', 'reponse')
->where('question.id_categorie = :id')
->setParameter('id', $id)
->getQuery()
->getResult();
}
I get that Error :
`An exception occurred while executing 'SELECT q0_.id AS id_0, q0_.id_categorie AS id_categorie_1, q0_.question AS question_2, r1_.id AS id_3, r1_.id_question AS id_question_4, r1_.reponse AS reponse_5, r1_.reponse_expected AS reponse_expected_6, r1_.question_id AS question_id_7 FROM question q0_, reponse r1_ WHERE q0_.id_categorie = ?' with params ["2"]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'r1_.question_id' in 'field list'`
I'm not sure to understand what do you want to do. But I suppose you want to get a question and the reponse related to this question.
For doing that, you need to make a join between those tables.
You can use for example leftJoin
$query->leftjoin('App\Entity\Reponse','reponse','WITH','reponse.id = question.reponse_id')
Note that i supposed that there is reponse_id in you question table.
Be free to replace it by what you want.
For more precisions, you can check doctrine documentation.
https://www.doctrine-project.org/index.html
There a lot of examples, tutorials and a fully documentation
[Edited]
Problem there was that the field question_id was not in the table question in the database
i am trying to get object from table orders with related attributes from table order_status_history. From table order_status_history, i need only last record with status 'Reviewing', so i use sort asc by field created_at. My code so far is , but i get error.
$orders = Order::GetOrderHistoryReviewing()->get();
public function scopeGetOrderHistoryReviewing($query)
{
return $query->whereHas('statusHistory', function($q) {
$q->where('status', 'Reviewing')->orderBy('created_at','desc')->first();
});
}
i need one object with relation from second table
this is my error
[2016-07-27 08:37:26] dev.ERROR: exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "orders"
LINE 1: ...ries" where "order_status_histories"."order_id" = "orders"."...
From your question, you're apparently trying to create a scope that returns orders with status, 'Reviewing' and sorts the results in descending order.
You need to remove the first() call from the $q subquery and move orderBy to the end of your $query. Your code should look like.
public function scopeGetOrderHistoryReviewing($query)
{
return $query->whereHas('statusHistory', function($q) {
$q->where('status', 'Reviewing');
})->orderBy('created_at','desc');
}
Then you can do:
$orders = Order::GetOrderHistoryReviewing()->get();
//OR to get the first record
$first_order = Order::GetOrderHistoryReviewing()->first();
I got this query:
$users = DB::table('users')->whereExists(function($query)
{
$query->select(DB::raw(1))
->from('galleries')
->whereRaw('galleries.user_id = users.id');
})->get();
This query selects all users who have gallery. Problem is that I can't use eloquent releationships now. Whenever i try to loop like this:
#foreach ($user->gallery as $gallery)
{{$gallery->name}}
#endforeach
I get error:
Undefined property: stdClass::$gallery
It happens with all other tables. What am I doing wrong here? My realationships are defined and they work just fine, i got problems only in this query. Thanks.
EDIT
Since it's not eloquent query, could you show me example how to write query, into few tables with eloquent. For example, I need all users who have their status approved in example table
First, determine a relationship in the User class, like this:
class User {
// Determine relation to Example table
public function examples() {
return $this->hasMany('Example', 'user_id', 'id'); // second parameter is the foreign key
}
}
Then the query:
User::whereHas('examples', function( $query ) {
$query->where('status','approved');
})->get();
Currently, a criteria BelongsToMany alerts and viceversa. They are related through a pivot table: criteria_id and alert_id.
I am getting all Criteria with the associated Alerts that belongs to the authenticated user, as such:
public function getMatches()
{
$matches = Criteria::whereUserId( Auth::id() )
->has('alerts')
->get();
}
This returns all associated results, whereas now, if a user picks a certain result, I want to be able to show just that. This is what I have so far:
Controller
public function getMatchDetails($alert_id, $criteria_id)
{
$matches = Alert::find($alert_id)
->has('criterias')
->where('criteria_id', $criteria_id)
->get();
}
Which is bringing over the correct variables, however, I am getting a MYSQL error:
Column not found: 1054 Unknown column 'criteria_id' in 'where clause'
select * from `alerts` where `alerts`.`deleted_at` is null and
(select count(*) from `criterias` inner join `alert_criteria` on `criterias`.`id` =
`alert_criteria`.`criteria_id` where `alert_criteria`.`alert_id` = `alerts`.`id`)
>= 1 and `criteria_id` = 7)
Any help would be hugely appreciated.
You could try something like this
public function getMatchDetails($alert_id, $criteria_id)
{
$match = Alert::whereHas('criterias', function ($q) use ($criteria_id) {
$q->where('criteria_id', $criteria_id);
})->find($alert_id);
}
Which will find the alert by id and also check that it has a relationship to criterias meeting those requirements.
I don't know if I understood well the question, but I'm going to try to answer
If you want to pass more than just a variable from the view to the controller, you can do something like this:
View
#foreach($matches as $match)
#foreach($match->alerts as $alert)
<td>{{$alert->pivot->criteria_id}}</td>
<td>{{$alert->id}}</td>
#endforeach
#endforeach
Controller
public function getMatchDetails($id, $var_2 = 0)
{
$myCriteriaIds = Criteria::whereUserId( Auth::id() )
->lists('id');
$match = Alert::find($id)->criterias()
->wherePivot('criteria_id', 'IN', $myCriteriaIds)
->get();
}
Route
Route::post('/users/alert/matches/{id}/{var_2}', array(
'as' => 'users-alert-matches',
'uses' => 'XXXController#getMatchDetails'
));