laravel postgres having method error with alias column - php

I made a search page with filters. In Laravel the code is:
$select = [
'car.id as id',
'car.car_name as name'
];
$q = Car::where('car.active',1);
if ($price) {
$select = array_merge([
DB::raw("(select p.car_price * $variable from prices p where p.car_id = car.id) as unique_price"
)],$select);
}
$q->select($select);
$q->having('unique_price', '>=', 2000);
I am using postgresql as laravel database and i get the error unique_price does not exist.
then i write:
dd($q->get());
and the "unique_price" column exists.
What is the problem? how can i fix it? in mysql works.

Related

Two Select from different table in Symfony

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

Query in Yi2 and checking a relationship in another table

I am trying to get data in a Yii2 table call Post. This table has an attribute call owner and I want to check whether the value of owner is equal to a particular Value I pass call it userId or the value of owner is equal to the following attribute of the Followship table where the value of the follower attribute of the Followship Table is equal to the the value I pass call it userId.
In implementing the above logically and bit by bit, I have written the following code;
$allpost = Post::find()->all();
$relevantpost = [];
foreach ($allpost as $post) {
if($post->owner == $userId){
$relevantpost[] = $post;
}
else{
$follower = Followship::findOne(['follower'=>$userId, 'following'=>$post->owner]);
if($follower){
$relevantpost[] = $post;
}
}
}
return $relevantpost;
This code works well but I want to write an active query for this such as ;
$allpost = Post::find()
->where(['owner'=>$userId])
->orWhere(['is NOT', $follower = Followship::findOne(['follower'=>$userId]) and 'owner' => $follower->following, NULL])
->all();
or in the worse case,
$allpost = \Yii::$app->db
->createCommand(
"SELECT postId, location, details, created_at FROM Post
WHERE owner = " . $userId. "OR
owner = '0' OR
owner = following IN (
SELECT following FROM Followship WHERE follower = ". $userId . " AND
)
ORDER BY dateCreated DESC"
)
->queryAll();
I keep getting errors with the above queries. I am missing out a fundamental of the Yii2 query builders.
Please any help on this will be greatly appreciated.
First you could make a relation (which connects Post and Followers by post owner) inside your Post class
class Post extends ActiveRecord {
public function getFollowersDataset() {
return $this->hasMany(Followers::className(), ['following' => 'owner']);
}
...
}
And then you can just use it in your queries
Post::find()
->joinWith('followersDataset')
->where(['or',
['owner' => $user_id],
['follower' => $user_id]])
->all()
The condition accept three parameters
[the_condition, the_attribute, the_value]
In case of AND and OR the thing change
[the_condition, first_condition, second_condition]
With the second tried you can make something like that
$allpost = Post::find()
->where(['owner'=>$userId])
->orWhere([
'AND',
['is NOT', $follower, Followship::findOne(['follower'=>$userId]),
['owner', $follower->following, NULL]
])
->all();
You can check in debug bar the querys that you're making, or another way, its to make a mistake in a field, for example if in your where condition you put ->where(['owners'=>$userId]), that trhow an error with the query that you made, so you can see what query you did

Datatable query using name rather than username

I have a project where we don't store the name of a user and just use their username for everything.
I cam across a package called Ticketit which is a helpdesk ticketing system for Laravel.
The package uses the name of users for everything and so this caused a few errors. I have a getNameAttribute() accessor on my User model and so for the most part this satisfies the package, however there were some places that explicitly called name in Eloquent ::lists() queries.
For these I manually replaced name with username inside my own fork of this repo, and have this linked up to my project.
The datatable loads as expected on the page, but when I try to sort by any of the other columns or run a search inside it I get 500 errors in my Network tab of developer tools.
Previewing the response shows this:
QueryException in Connection.php line 662:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.name' in 'where clause' (SQL: select count(*) as aggregate from (select '1' as row_count from ticketit inner join users on users.id = ticketit.user_id inner join ticketit_statuses on ticketit_statuses.id = ticketit.status_id inner join ticketit_priorities on ticketit_priorities.id = ticketit.priority_id inner join ticketit_categories on ticketit_categories.id = ticketit.category_id where completed_at is null and (LOWER(ticketit.id) LIKE %%h%% or LOWER(subject) LIKE %%h%% or LOWER(ticketit_statuses.name) LIKE %%h%% or LOWER(ticketit.updated_at) LIKE %%h%% or LOWER(users.name) LIKE %%h%% or LOWER(ticketit_priorities.name) LIKE %%h%% or LOWER(users.name) LIKE %%h%% or LOWER(ticketit_categories.name) LIKE %%h%%)) count_row_table)
Following the route this posts to, I get to TicketController#data. In the original package this is:
public function data(Datatables $datatables, $complete = false)
{
$user = $this->agent->find(auth()->user()->id);
if ($user->isAdmin()) {
if ($complete) {
$collection = Ticket::complete();
} else {
$collection = Ticket::active();
}
} elseif ($user->isAgent()) {
if ($complete) {
$collection = Ticket::complete()->agentUserTickets($user->id);
} else {
$collection = Ticket::active()->agentUserTickets($user->id);
}
} else {
if ($complete) {
$collection = Ticket::userTickets($user->id)->complete();
} else {
$collection = Ticket::userTickets($user->id)->active();
}
}
$collection
->join('users', 'users.id', '=', 'ticketit.user_id')
->join('ticketit_statuses', 'ticketit_statuses.id', '=', 'ticketit.status_id')
->join('ticketit_priorities', 'ticketit_priorities.id', '=', 'ticketit.priority_id')
->join('ticketit_categories', 'ticketit_categories.id', '=', 'ticketit.category_id')
->select([
'ticketit.id',
'ticketit.subject AS subject',
'ticketit_statuses.name AS status',
'ticketit_statuses.color AS color_status',
'ticketit_priorities.color AS color_priority',
'ticketit_categories.color AS color_category',
'ticketit.id AS agent',
'ticketit.updated_at AS updated_at',
'ticketit_priorities.name AS priority',
'users.name AS owner',
'ticketit.agent_id',
'ticketit_categories.name AS category',
]);
$collection = $datatables->of($collection);
$this->renderTicketTable($collection);
$collection->editColumn('updated_at', '{!! \Carbon\Carbon::createFromFormat("Y-m-d H:i:s", $updated_at)->diffForHumans() !!}');
return $collection->make(true);
}
Which I have edited to this in my fork:
public function data(Datatables $datatables, $complete = false)
{
$user = $this->agent->find(auth()->user()->id);
if ($user->isAdmin()) {
if ($complete) {
$collection = Ticket::complete();
} else {
$collection = Ticket::active();
}
} elseif ($user->isAgent()) {
if ($complete) {
$collection = Ticket::complete()->agentUserTickets($user->id);
} else {
$collection = Ticket::active()->agentUserTickets($user->id);
}
} else {
if ($complete) {
$collection = Ticket::userTickets($user->id)->complete();
} else {
$collection = Ticket::userTickets($user->id)->active();
}
}
$collection
->join('users', 'users.id', '=', 'ticketit.user_id')
->join('ticketit_statuses', 'ticketit_statuses.id', '=', 'ticketit.status_id')
->join('ticketit_priorities', 'ticketit_priorities.id', '=', 'ticketit.priority_id')
->join('ticketit_categories', 'ticketit_categories.id', '=', 'ticketit.category_id')
->select([
'ticketit.id',
'ticketit.subject AS subject',
'ticketit_statuses.name AS status',
'ticketit_statuses.color AS color_status',
'ticketit_priorities.color AS color_priority',
'ticketit_categories.color AS color_category',
'ticketit.id AS agent',
'ticketit.updated_at AS updated_at',
'ticketit_priorities.name AS priority',
'users.username AS owner',
'ticketit.agent_id',
'ticketit_categories.name AS category',
]);
$collection = $datatables->of($collection);
$this->renderTicketTable($collection);
$collection->editColumn('updated_at', '{!! \Carbon\Carbon::createFromFormat("Y-m-d H:i:s", $updated_at)->diffForHumans() !!}');
return $collection->make(true);
}
With this I have changed the users.name to users.username, but this isn't fixing the issue for me.
Can anyone help me figure out why, or what else I need to change as I haven't had any luck figuring out where else I need to change this.
You'll drive yourself nuts trying to edit all the places where the 3rd-party code tries to access name. My suggestion is to fix at the root rather than patch in many places:
Create a new name column in users table
Fill that column with the values in the username column
eg queries:
ALTER TABLE `users` ADD COLUMN `name` VARCHAR(30) NOT NULL AFTER `username`;
UPDATE `users` SET `name` = `username`;
Now your DB will have the schema that your plugin expects.
I found the issue, it was in the initialisation of the DataTable where it was calling users.name rather than users.username.
After updating this, clearing the views cache php artisan view:clear it all worked fine!

How to count_all() in Kohana 3.3 with Mysqli drivers

I am trying to use the count_all() method in kohana 3.3 to count all the rows of a table where the id equals a user_id. Here is my controller
public function action_get_messages()
{
$user_id = $this->request->param('id');
$messages = new Model_Message;
if ($user_id)
{
$messages = $messages->where('user_id', '=', $user_id);
$messages->reset(FALSE);
$message_count = $messages->count_all();
}
else
{
$message_count = $messages->count_all();
}
$pagination = Pagination::factory(array(
'total_items' => $message_count,
'items_per_page' => 3,
));
$pager_links = $pagination->render();
$messages = $messages->get_all($pagination->items_per_page, $pagination->offset, $user_id);
$this->template->content = View::factory('profile/messages')
->set('messages', $messages)
->set('pager_links', $pager_links);
}
But when i run the code i get these error message:
"Database_Exception [ 1054 ]: Unknown column 'COUNT("*")' in 'field list' [ SELECT COUNT("*") AS records_found FROM messages
AS message WHERE user_id = '2' ]"
What does this error mean and where is the error in my code?
Thanks in advance!
The error is on line 1054, which I would guess is the count_all() call.
I'm confused as to why you are calling a reset() on your object. This may be causing issues. You are also casting the object to itself, which is unnecessary. That section of code could look like this:
if ($user_id)
{
$messages->where('user_id', '=', $user_id);
$message_count = $messages->count_all();
}
I would advise using the ORM::factory to build your new models in the first place.
The Kohana documentation isn't great, but I would advise reading and looking through the ORM User Guide as ORM will save you a hell of a lot of time in the long run, especially if it's a large project.

Yii Get data from another model using Relation

I am trying to filter a table in my view using the search function in my model.
I have two models which i need to get data from model Evaluation to another model EvaluationDetails.
i have this in my EvaluationDetails model
public function relations() {
return array(
'eval' => array(self::BELONGS_TO, 'Evaluation', 'eval_id'),
);
}
i also have this in my search function
public function search($employee = '', $search_date_start = '', $search_date_end = '', $search = '') {
$criteria = new CDbCriteria;
$criteria->with = array('eval' => array('together' => true));
$criteria->compare('employee_id', $this->employee_id);
$criteria->compare('remarks', $this->remarks, true);
$criteria->compare('eval_id', $this->eval_id);
$criteria->compare('eval.evaluatee', $this->evaluatee_search);
$criteria->addSearchCondition('eval.evaluatee', $search);
if ($employee != '')
$criteria->compare('employee_id', $employee->company_id);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
I am trying to filter a table where in the user will search for a name, pass the value in $search which is then used in the search function in my EvaluationDetails model
With this, i am getting an error.
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]:
Integrity constraint violation: 1052 Column 'employee_id' in where
clause is ambiguous. The SQL statement executed was: SELECT
COUNT(DISTINCT t.id) FROM trx_evaluation_details t LEFT OUTER
JOIN trx_evaluation eval ON (t.eval_id=eval.id) WHERE
((eval.evaluatee LIKE :ycp0) AND (employee_id=:ycp1))
what seems to be the problem with my code. please help..
Seeing from the error message, it looks like both EvaluationDetails and Evaluation have a field call "employee_id" (i am not sure)
But if so, you need to replace the
$criteria->compare('employee_id', $employee->company_id);
with
$criteria->compare('t.employee_id', $employee->company_id);
To explicitly tell yii the field is from EvaluationDetails table.
BTW, u are using $employee->company_id (should be $employee->employee_id ?)

Categories