Issue in building search with like query using QueryBuilder yii2 - php

I am trying to make a search query for my website blogs using yii2 QueryBuilder , but there is an error like this when i try to execute my query with ->all() . here is the error : strtr() expects parameter 1 to be string, object given . And here is my model and controller . I have no idea what is causing the problem .
controller :
public function actionSearchBlog()
{
$model = new Blog();
if ($model->load(Yii::$app->request->post())) {
Blog::searchBlog($model->search);
} else {
return $this->render('search',['model' => $model]);
}
}
Model :
public static function searchBlog($search = null)
{
$search = new Query();
$result = $search->select('id','title','blog','picture')
->from('blog')
->where(['like' , 'title' , $search])
->orWhere(['like' , 'blog' , $search])
->all();
echo '<pre>';
var_dump($result);
die();
}
I tried the query without ->all() at the end , but the var_dump value will be the the query itself and it won't be executed . and with ->all() I get that error.

public static function searchBlog($search = null)
{
$query = new Query();
$result = $query->select('id','title','blog','picture')
->from('blog')
->where(['like' , 'title' , $search])
->orWhere(['like' , 'blog' , $search])
->all();
echo '<pre>';
var_dump($result);
die();
}
This will work. But start using IDE, and watch on variables you are using.

Try your ActiveQuery as:--
$result = (new Query())->select('id','title','blog','picture')
->from('blog')
->where(['like' , 'title' , $search])
->orWhere(['like' , 'blog' , $search])
->all();
echo '<pre>';
var_dump($result);
die();

Are you sure the $search is string or array?
like: operand 1 should be a column or DB expression, and operand 2 be
a string or an array representing the values that the column or DB
expression should be like. For example, ['like', 'name', 'tester']
will generate name LIKE '%tester%'.
When the value range is given as an array, multiple LIKE predicates
will be generated and concatenated using AND. For example, ['like',
'name', ['test', 'sample']] will generate name LIKE '%test%' AND
name LIKE '%sample%'. The method will properly quote the column name
and escape special characters in the values.
Sometimes, you may want to add the percentage characters to the
matching value by yourself, you may supply a third operand false to
do so. For example, ['like', 'name', '%tester', false] will generate
name LIKE '%tester'.

Related

Semantical error when using QueryBuilder with an expression

I have a problem with getting data from the database using the expr() method function. I would like to get data where isPublic = true and objectType = $objectType OR user = $user and objectType = $objectType, no matter what the value of isPublic is.
I'm getting this error:
[Semantical Error] line 0, col 76 near 'user-avatar)': Error: 'user' is not defined.
My code in repository:
public function findByObjectType($objectType, $user)
{
$qb = $this->createQueryBuilder('s');
return $qb->where($qb->expr()->andX(
$qb->expr()->eq('s.isPublic', true),
$qb->expr()->eq('s.objectType', $objectType)
))
->orWhere($qb->expr()->andX(
$qb->expr()->eq('s.user', $user->getId()),
$qb->expr()->eq('s.objectType', $objectType)
))
->getQuery()
->getResult();
}
where: $objectType = 'user-avatar'; $user = UserInterface
expr()->eq() will treat the expression as literals, trying to use them literally as they appear on method call.
As mentioned by the library author:
You are not using parameter binding. Expressions use string concatenation internally, so this outcome is actually expected.
In your case, you should be doing something like::
return $qb->where($qb->expr()->andX(
$qb->expr()->eq('s.isPublic', ':true'),
$qb->expr()->eq('s.objectType', ':objectType')
))
->orWhere($qb->expr()->andX(
$qb->expr()->eq('s.user', ':userId'),
$qb->expr()->eq('s.objectType', ':objectType')
))
->setParameter('true', true)
->setParameter('userId', $user->getId())
->setParameter('objectType', $objectType)
->getQuery()
->getResult();
This way your code is easier to read, safer and more portable.
When using $qb->expr()->eq() you will need supply the exact value for the query. In this case you need to change your query to something like this:
$qb->expr()->eq('s.objectType', '"' . $objectType .'"')
This way to string will be correctly quoted in the db query. The same goes for booleans by the way. Casting true to a string will result in 1. That's why you didn't encounter an error in this case. false however gets cast to an empty string, which would result in an error.
To better understand what's going on, here is the part of code that converts the eq() expression to the query:
/**
* #return string
*/
public function __toString()
{
return $this->leftExpr . ' ' . $this->operator . ' ' . $this->rightExpr;
}

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

How to pass array in where condition of Query with one "Not Equal" Condition

I am working on Laravel 5.2. I faced a problem for sending an array to model function with one on my value is Not Equal.
I check this way is working:
$users = DB::table('users')
->where([ ['status','1'], ['subscribed','!=','1'], ])
->get();
But in my case, i am working in a reusable function:
$whereData = array('name'=>'test' , 'id !=' => '5');
$users = DB::table('users')->where($whereData)->get();
Here Not Equal to condition not working and provides error. What is correct syntax for using this reusable function with whereData array consists of multiple operators like "!= , <> , etc ...".
I would suggest you the following way.
Only send the data without where condition.
Therefore,
$whereData = array('name'=>$username , 'statusid' => $userid);
$users = DB::table('users')->where('status', '=', $whereData['name'])->orWhere('subscribed', '<>', $whereData['statusid'])->get();
or as you mentioned, replace where with whereColumn
Thus the code will be,
$whereData = array( array('name','test') , array( 'id','<>','5'));
$users = DB::table('users')->whereColumn($whereData)->get();

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 ?)

How to use "where in" method in codeigniter?

Hello Everybody i have problem with my program i need check multi number in my database but when i test it just show only one result my code :
/*in mt View*/
$data = array(
'name' => 'search_id',
'id' => 'search_id',
'placeholder' => 'numbers_test',
'autofocus' =>"autofocus",
'rows' => '20'
);
echo form_textarea($data,set_value('search_id'));
/* in my model */
$this->db->select('*');
$this->db->from('personal_info');
$this->db->where_in('p_id', $this->input->post('search_id'));
return $this->db->get();
i waiting your help for this problem
If you are getting input as comma separated ids like in string 1,5,4,8 etc from $this->input->post('search_id') then update your code like this
/* in my model */
$this->db->select('*');
$this->db->from('personal_info');
// Explode string into array to make where_in clause work
$this->db->where_in('p_id', explode(',', $this->input->post('search_id')));
return $this->db->get();
as official docs suggest you need to provide array of options in IN clause
You have to return the result of the query. Make changes,
/* In my model */
$this->db->select('*');
$this->db->from('personal_info');
$this->db->where_in('p_id', $this->input->post('search_id'));
$query = $this->db->get();
return $query->result_array(); // You've to return the result of the query
Also as #Saqueib said in comments, try some debugging when in doubt,
echo $this->db->last_query(); exit;
OR
echo '<pre>'; print_r($query->result_array()); exit;

Categories