Rails - Writing a Where Query With an Or Clause - mysql

I'm having trouble figuring out how to combine to queries into one with my Rails 5 app (mySQL). I want #activities to return the Activity records that meet the criteria for Query 1 or 2.
Can someone please help me? Thank you!
Query 1
#activities = Activity.where(owner_id: current_user.friend_ids, owner_type: "User")
Query 2
#activities = Activity.where(recipient_id: current_user.id)

Try this ............
#activities = Activity.where("(owner_id in = ? and owner_type = ?) or recipent_id = ?", current_user.friend_ids,"User",current_user.id )
For Rails 5 :
#activities = Activity.where(owner_id: current_user.friend_ids, owner_type: "User").or(Activity.where(recipient_id: current_user.id))
Hope this will work for you.

Try the below
#activities = Activity.where("(owner_id in = ? and owner_type = ?) or recipent_id = ?", current_user.friend_ids,"User",current_user.id )
or
#activities = Activity.where(owner_id: current_user.friend_ids, owner_type: "User").or(Activity.where(recipient_id: current_user.id))

using AREL is a great way to get OR or AND queries going, its a more programatic way of getting the SQL queries you want as you can build them up and meta program them in easily, and it avoids using direct SQL strings which can get too big and complex and unreadable, but here is a snippet for your code to get you going:
table = Activity.arel_table
query = arel_table['owner_id'].in(current_user.friend_ids).and(arel_table['owner_type'].eq("User"))
query = query.or(arel_table['recipient_id'].eq(current_user.id))
#activities = Activity.where(query)
I strongly recommend looking up more about using AREL, here are some pages to see more:
definitive guide to arel
using arel to compose sql queries
EDIT
For some reason I decided to completely ignore the fact that you are runnin rails 5, in which case Akshay's answer / Chakreshwar Sharma's second answer is definately the way to go.
However I still recommend learning about and getting to grips with AREL is it can really help out in a lot of other cases where you might have more complex queries to write!

you can also use this way:
# load all ids for owner
activity_ids_by_owner = Activity.where(owner_id: current_user.friend_ids, owner_type: "User").pluck(:id)
# load all ids for recipient
activity_ids_by_recipient = Activity.where(recipient_id: current_user.id).pluck(:id)
# load all activities for founded ids
Activity.where(id: activity_ids_by_owner | activity_ids_by_recipient)

Related

Laravel update query (Add a value to existing a value)

I am trying to update a record using Laravel.
I have gone through lot of StackOverflow Questions to check whether this question is already raised.
mysql query : UPDATE students SET total_marks = total_marks + 80 WHERE id = 1
I have to translate this mysql query into Laravel query builder, but couldn't get a solution yet.
Instead of getting the early value from DB before update, Can we update the table with one update query using Laravel Query Builder.
2 Queries way:
$student_marks = Students::select('total_marks')->where('id','=',1);
$current_mark = $student_marks['total_marks']+80;
$update_student_marks = Students::where('id','=',1)->update('total_marks','=',$current_mark);
How to update a record like this with single query builder in Laravel.
I think you need to make a few adjustments to your query.
First, you need to select the student correctly and than use Eloquent to call save method on it after setting the property to the correct value. I assume you are on Laravel 6.
$student_marks = Students::find($id);
$student_marks->total_marks += 80;
$student_marks->save();
Please, take a look at Laravel docs:
https://laravel.com/docs/6.x/eloquent
The reading takes some time but its definitely worth it. You will learn how to deal with eloquent and make your code better by using the most appropriate techniques.
You can use the save function for this.
$student_marks = Students::select('total_marks')->where('id','=',1);
$student_marks->total_marks += 80; //or $student_marks->total_marks = $student_marks->total_marks + 80;
$student_marks->save();
Pass update data as array
Try this way
$update = array('total_marks'=>$current_mark);
$update_student_marks = Students::where('id','=',1)->update($update);

Rails SQL QUERY Like

I've some problem with an SQL Query
I've users which have skills
def skills=(value)
super(value.reject(&:blank?).join("|")) if !value.nil?
end
def skills
super.present? ? super.split("|") : []
end
Here is my problem. When I query on this field with "like", word order matter. How can I avoid that ?
User.where("skills LIKE '%car%driving_license%'")
Each user with skills which at least contain car and driving_license
User.where("skills LIKE '%driving_license%car%'")
Each user with skills which at least contain car and driving_license but in a different order
I want to be able to avoid this order problem. Any help ?
If you sort the skills you can know the order and assemble a like query that will match both of them. You can create a migration to sort the existing skills.
def skills=(value)
super(value.reject(&:blank?).sort.join("|")) if value
end
rails g migration sortUserSkills
User.where.not(skills: nil).each do u
u.skills = u.skills
u.save
end
LIKE + OR queries are tough if my memory serves me. You can try ARel, but I think you lose LIKE.
2 things I can think of:
Do the queries separately and combine results.
Use something like this which may not work:
conditions = ['%driving_license%car%', '%car%driving_license%']
User.where("skills LIKE ?", conditions)

get sql query from collection model

I know that we can get sql query from magento model collection using this,
getSelect();
But I can get query from only the model collections, not worked in others or May be I dont know how to use it.
Here I want to know what query is running behind this,
$productModel = Mage::getModel('catalog/product')->getCollection();
$attr = $productModel->getResource()->getAttribute("color");
if ($attr->usesSource()) {
echo $color_label = $attr->getSource()->getOptionText("28");
}
If I use this,
echo $productModel->getSelect(); exit;
I'm just get the one part the query only, like,
SELECT `e`.* FROM `catalog_product_entity` AS `e`
Update:
This is my full code,
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
$productModel = Mage::getModel('catalog/product')->getCollection();
$attr = $productModel->getResource()->getAttribute("color");
if ($attr->usesSource()) {
$color_label = $attr->getSource()->getOptionText("28");
}
$productModel->printlogquery(true);exit;
Please help me guys,
Your order condition is not visible in the query. The reason your order isn't showing is because the orders are added to the query during the load() method.
See Varien_Data_Collection_Db::load()
Try calling load(true) to see the complete SQL containing the order by clause.
$productModel->load(true);
$productModel->printLogQuery(true);
Hope it helps.
If you want to see what is the exact query, then you can get this by using:
$productModel->printlogquery(true);exit;
Use this code after you have loaded your model's object and applied all conditions.
I hope this will help you.
Magento collecting data with lot of internal queries - models and lot of checks, and may be more than 1 table. So it is not possible to get the query like what I'm looking for.

Multi-table generic query model for CakePHP

I have approximately 25 join queries I need to build to run in a project on CakePHP.
It is much faster to just work in MySQL WorkBench or phpMyAdmin building the queries,
and then drop into PHP code than to use the screwed up cakePHP model parms that many times
have no one-to-one relationship to a MySQL query.
Is there a no-table or multi-table "take anything MySQL" example that reduces or eliminates the CakePHP complexity?
TLDR:
Use the Model's query() method to write any MySQL you'd like.
More details:
It sounds like you haven't actually read through the book. Should probably try that before bashing things that you don't understand.
For anyone else who might want to learn how to join things in CakePHP:
How to Join using CakePHP
And
How to run any MySQL query in CakePHP
CakePHP provides Model::query() for you to have more control. I'd be inclined that you use prepared statements too, if you really want to let go of CakePHP's find methods.
$db = $this->getDataSource();
$db->fetchAll(
'SELECT * from users where username = ? AND password = ?',
array('jhon', '12345')
);
$db->fetchAll(
'SELECT * from users where username = :username AND password = :password',
array('username' => 'jhon','password' => '12345')
);
Here is a note:
query() does not honor $Model->cacheQueries as its functionality is
inherently disjoint from that of the calling model. To avoid caching
calls to query, supply a second argument of false, ie: query($query,
$cachequeries = false)

Preparing mySQL query with where

I'm trying to make a mySQL query that updates a field called "connected" to 1 ONLY IF user1 = derp AND user2=derpette or the opposite. I'm having ad difficult time with the syntax. I read some of the other threads on overflow, which led me to creating the following query. If anyone could provide me any suggestions towards the correct syntax or perhaps provides an alternate solution to this problem, it would be greatly appreciated. Thanks.
UPDATE xGames
SET connected = 1
WHERE ((user1 = 'derp' AND user2 = 'derpette')
OR (user2='derpette' AND user1='derp'))
I'm not sure if you're getting a syntax error, or if it just isn't behaving as you expect, but you didn't reverse the conditions - you only reversed the ORDER of the same conditions...
UPDATE xGames
SET connected = 1
WHERE ((user1 = 'derp' AND user2 = 'derpette')
OR (user1='derpette' AND user2='derp'));