find all using distinct query in Cakephp - sql

I am newbie in cakephp and trying to implement this query
SELECT DISTINCT mobilenO,DATETIME
FROM textmessage;
what i am trying right now is this
$this->find('all',array(
'fields'=>array('Message.dateTime', 'DISTINCT Message.mobileNo'),
'order'=>'Message.idTextMessage DESC',
'conditions' => array('Message.User_id' => $userid)));
It is throwing me errors. I actually want to select only distinct or unique numbers from db. I have added the distinct in my query, but it didnt work.

i have to use distinct first not after 1st column.. dont know why but it works
$this->find('all',array(
'fields'=>array('DISTINCT mobileNo','dateTime'),
'order'=>'Message.idTextMessage DESC',
'conditions' => array('Message.User_id' => $userid)));

Related

"andFilterWhere" work proper with "joinWith()" but not with "with()" in yii2

I am working in yii2.
There are employee and company table employee contains company_id.
I have a filter search running properly If I use joinWith()
$query = Employee::find();
$query->joinWith(['company']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
'sort' => false,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
//and below is the filterwhere
$query->andFilterWhere(['like', 'company.name', $this->company_id]);
But issue came when I make a query using with()
$query = Employee::find()->with(['company']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
'sort' => false,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
//when query contain with() then this filter is not working.
$query->andFilterWhere(['like', 'company.name', $this->company_id]);
This gives error when I use with()
Database Exception – yii\db\Exception
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'company.name' in 'where clause'
The SQL being executed was: SELECT COUNT(*) FROM `employee` WHERE `company`.`name` LIKE '%1%'
Here is the relation in employee with company:
public function getCompany(){
return $this->hasOne(Company::className(), ['id'=> 'company_id']);
}
Can anyone help me or guide me how could I filter data properly using with() in a query?
Thanks.
You can't swap joinWith() and with() methods when you need to filter by the column from the related table. That's because these methods does completely different things.
Methods like joinWith() and join() actually modifies the query to add the "JOIN" part to the SQL query. The with in joinWith allows you to specify the joined table by the relation definition in the model. The eager loading in joinWith is only side effect and you can even turn that off by passing false as second parameter.
When you do:
Employee::find()->joinWith(['company'])->all();
The query that is run looks like:
SELECT * FROM employee LEFT JOIN company ON (...)
On the other side the method with() doesn't modify the query itself. It only forces the eager loading of related models. In reality the second query is used for preloading the related records.
When you do:
Employee::find()->with(['company'])->all();
It actually runs queries like these:
SELECT * FROM employee;
SELECT * FROM company WHERE id IN (...company ids selected in first query...);
So when you try to do:
$query = Employee::find()
->with(['company'])
->andFilterWhere(['like', 'company.name', $this->company_id])
->all();
The generated query is
SELECT * FROM employee WHERE company.name LIKE ...

wordpress wp query posts & meta value

I have a cpt "members".
In a post I can select multiple members (object) via ACF in the specific post.
Now I want say: Please give me all posts where a member (e.g. nr. 76) ist marked in the post.
I try the whole day, and have no idea.
It's possible if i change the acf field to one number to get the correct posts, but Its important that I can select multiple members.
Thanks for helping!
Finally got it :-)
$args = array(
'post_type'=>'post',
'numberposts'=> -1,
'meta_query' => array(
array(
'key' => 'members',
'value' => '76', //example
'compare'=>'LIKE'
)
)
);

Jenssegers / select('column') returns more columns than the one specified in the select

I have the following issue with jenssegers query builder (I'm a new user):
print_r(DB::table($tablename)->where('_id',$_id)->select($table_structure_record['field'])->get());
returns me more than one column, despite only one column is specified in the select statement:
Array ( [0] => Array ( [_id] => MongoDB\BSON\ObjectID Object ( [oid] => 5780b81d93f7fb0e00d0f252 ) [collection] => structure ) )
My expected result would be only ([collection] => structure) , I don't understand why i also get "[_id] => MongoDB\BSON\ObjectID Object ( [oid] => 5780b81d93f7fb0e00d0f252 )"
Can someone help me ? Despite many searches, it seems select statement is supposed to return ONLY the columns specified, not any other !
MongoDb always returns the _id field unless you specifically set it not to while making the request(MongoDb Limit Fields to Return from Query Documentation).
You can try using project instead.Then it will be something like this:
DB::table($tablename)->where('_id',$_id)->project([$table_structure_record['field'] => 1, "_id" => 0])->get());

Sugar query syntax error in SugarCRM

I am trying to join table prospects with leads. I am executing this query
$queryProspects = new SugarQuery();
$queryProspects->from(BeanFactory::getBean('Prospects'));
$leads = $queryProspects->joinTable('leads');
$queryProspects->select("prospects.id","prospects.lead_id");
$queryProspects->where()->equals("lead_id","117c3d5d-07d9-0ae7-5610-573ac87c9a35");
Before executing it like this.
$queryProspects->execute();
I am compiling my query like
$queryProspects->compileSql();
This query is not working after executing. query result after compiling is
SELECT prospects.id id, prospects.lead_id lead_id FROM prospects JOIN leads ON () WHERE prospects.deleted = 0 AND prospects.lead_id = '117c3d5d-07d9-0ae7-5610-573ac87c9a35'
I know the error is () WHERE which I need to remove, but unable to do changes in sugar query in order to remove these brackets and where clause (which are showing in sql generated query).
Change from and join statement like this.
$queryProspects->from(BeanFactory::getBean('Prospects'), array('team_security' => false));
$leads = $queryProspects->join('lead')->joinName();
lead in join is the link (name field) in your prospects > vardefs.php as shown below.
'lead' => array(
'name' => 'lead',
'type' => 'link',
'relationship' => 'lead_prospect',
'module' => 'Leads',
'source' => 'non-db',
'vname' => 'LBL_LEAD',
),
please execute your query like this :
$result = $queryProspects->execute();
For more details Follow this link :
Sugar Query

Struggle with SQL Statement (Not Exists)

Hey i have some problems with a sql statement. This is the Database Scheme:(http://docs.elgg.org/wiki/DatabaseSchema), only the "entities" and the "relationship" table are important! What i'm trying to do is, select all guid's where the type of the object is "group" but this object is not a child of a other group. That means there is no record in the relationship table with the guid in the guid_two column. My first idea was this:
SELECT * FROM elgg_entities e
JOIN elgg_entity_relationships r ON e.guid = r.guid_one
WHERE e.type='group' AND NOT EXISTS (
SELECT *
FROM elgg_entity_relationships s
WHERE e.guid = s.guid_two
AND s.relationship='subgroup')
But it wont work. Also there are some other relationships in the table like member etc. I hope someone can help me, because i really frustrated right now.
Edit: This SQL query works in MyPHP, in elgg i tried to convert it into "elgg-ich":
$options = array(
'type' => 'group',
'joins' => array("JOIN elgg_entity_relationships r ON e.guid = r.guid_one"),
'wheres' => array("e.type='group' AND not exists (SELECT e.guid
FROM elgg_entity_relationships s
where e.guid = s.guid_two
AND s.relationship = 'subgroup'
)"),
'limit' => $limit,
'full_view' => FALSE,
);
$content = elgg_list_entities($options);
=> Solution was the case sensitivity and where instead of wheres in line 6.
As noted in the edited question;
Solution was the case sensitivity and where instead of wheres in line
6.