How to bind value sql query in laravel? - laravel

I have a query. Query is include sql function. So I want to directly. But I need parameter.
$parameters = DB::select("SELECT GetFlowPropertyValue(flow.id, 'PCommonLineDataNumber') subscriberNumber, (SELECT Id FROM ConfigurationItem WHERE FlowId = flow.id ORDER BY Id DESC Limit 1) ConfigurationItemId, GetObjectTypeRelationParentObjectValue(6, 1, flow.id) CustomerId, GetFlowPropertyValue(flow.id, 'MainOfferingName') MainOfferingName, GetFlowPropertyValue(flow.Id, 'CampaignName') CampaignName FROM akislar flow WHERE id ='$query->id'");
As you can see, Final parameter come foreach but doesnt run. I use dd and I write query.
I see $query->id is look like empty. It is not defined.
How can I bind $query->id ?

Related

Eloquent : Creating additional row with alias to the result set

Suppose I have a user table with columns id, name, age
With a normal get query User::get(), I get all results with those column's value.
But instead of just getting the id, name, age columns, is it possible if I add another column, perhaps a column with an alias of future_age with a value of age + 1.
The above result could be achieved in SQL like so:
SELECT res.*, (SELECT sum(res.age+1) from users where id = res.id) as future_age from users as res
I've thought about looping through the result and creating new key. but I think this would make the query execution time slow when the data is lengthy.
Is it possible to create the future_age key/column (I don't know the term hehe) directly on the query?
Currently, this is my query:
$user = User::get();
$new_res = []
if($user->count() > 0) {
foreach ($user as $u) {
$u['future_age'] = $u->age + 1
$new_res[] = $u;
}
}
The query works tho, but I don't think this is good if I have a large set of data.

Query date field in Yii2

In SQL, I might do something like this
"WHERE DATEPART(month, my_date_field) = 8"
to grab the rows where month in my_date_field = 8.
I am unsure how this syntax translates into Yii2.
I have
$query = Fees::find();
$fees = $query->all();
How do I use the WHERE clause on the date field within that $query ?
The query in yii2 allows text in where clause as below
$fees = Fees::find()
->where("DATEPART(month, my_date_field) = 8")
->all();
You may chain other 'sql functions' like order, group by , limit etc like this as well.

SQL Group by and having in coherence

I would like to execute the following query in Coherence
Select AVG(Salary)
, Count(*)
from Employees
group by Company
Having AVG(Salary)> 1000
I was trying to use GroupAggregators but I have problem with refering to an avarage salary as it is not defined in the Employee Class but in Aggregator:
GroupAggregator high_salary = GroupAggregator.createInstance("getDepartment"
, new DoubleAverage("getSalary")
, new GreaterFilter("DoubleAverage", 1000));
How can I do this?
You should use IdentityExtractor.INSTANCE instead of "DoubleAverage" as a value extractor in GreaterFilter, because value passed to this filter is the avarage salary itself, not some object with "DoubleAverage" property.
But if you would like to get avarage salary as well as count (that would be consistent with your SQL query), you will have to use CompositeAggregator. In that case the value passed to the filter will not be a number anymore, but a List and you will have to use ValueExtractor that will extract avarage salary from this list. In Coherence 12.2.1 it would look like this:
DoubleAverage<Employee> avgSalary = new DoubleAverage<>(Employee::getSalary);
Count<String, Employee> count = new Count<>();
CompositeAggregator<String, Country> compositeAggregator = CompositeAggregator
.createInstance(new InvocableMap.EntryAggregator[] { avgSalary, count });
ValueExtractor<Object, ? extends Double> salaryExtractor =
list -> ((List<Number>) list).get(0).doubleValue();
Filter having = Filters.greater(salaryExtractor, 1000.0);
GroupAggregator<String, Country, Employee, String, List> groupAggregator =
GroupAggregator.createInstance(Employee::getDepartment, compositeAggregator, having);
It can be done also in older versions, but it would require some more work to implement salaryExtractor without using lambda expression.

CodeIgniter query in associative array

Please tell me how to pass OR condition in CodeIgniter query. My query like:
$where=array('status' => 'pending','linux_added_on >='=>$from_date,'linux_added_on <='=>$to_date);
And I want to add:
$where=array('status' => 'pending OR Approve','linux_added_on >='=>$from_date,'linux_added_on <='=>$to_date);
Please help me.
Here is an example. Change query to your needs:
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
The question marks in the query are automatically replaced with the values in the array in the second parameter of the query function.

Symfony2 subquery within Doctrine entity manager

I need to perform this query:
SELECT * FROM (SELECT * FROM product WHERE car = 'large' ORDER BY onSale DESC) AS product_ordered GROUP BY type
In Symfony2 using the entity manager.
My basic query builder would be :
$query = $em->getRepository('AutomotiveBundle:Car')
->createQueryBuilder('p')
->where('pr.car = ?1')
->andWhere('pr.status = 1')
->orderBy('pr.onSale', 'DESC')
->setParameter(1, $product->getName())
->groupBy('p.type')
->getQuery();
But I cannot work out how to add in a subquery to this.
Ive tried making a separate query and joining it like:
->andWhere($query->expr()->in('pr.car = ?1',$query2->getQuery()));
But I get:
Call to undefined method Doctrine\ORM\Query::expr()
One trick is to build two queries and then use getDQL() to feed the first query into the second query.
For example, this query returns a distinct list of game ids:
$qbGameId = $em->createQueryBuilder();
$qbGameId->addSelect('distinct gameGameId.id');
$qbGameId->from('ZaysoCoreBundle:Event','gameGameId');
$qbGameId->leftJoin('gameGameId.teams','gameTeamGameId');
if ($date1) $qbGameId->andWhere($qbGameId->expr()->gte('gameGameId.date',$date1));
if ($date2) $qbGameId->andWhere($qbGameId->expr()->lte('gameGameId.date',$date2));
Now use the dql to get additional information about the games themselves:
$qbGames = $em->createQueryBuilder();
$qbGames->addSelect('game');
$qbGames->addSelect('gameTeam');
$qbGames->addSelect('team');
$qbGames->addSelect('field');
$qbGames->addSelect('gamePerson');
$qbGames->addSelect('person');
$qbGames->from('ZaysoCoreBundle:Event','game');
$qbGames->leftJoin('game.teams', 'gameTeam');
$qbGames->leftJoin('game.persons', 'gamePerson');
$qbGames->leftJoin('game.field', 'field');
$qbGames->leftJoin('gameTeam.team', 'team');
$qbGames->leftJoin('gamePerson.person', 'person');
// Here is where we feed in the dql
$qbGames->andWhere($qbGames->expr()->in('game.id',$qbGameId->getDQL()));
Kind of a long example but i didn't want to edit out stuff and maybe break it.
You can use DBAL for performing any sql query.
$conn = $this->get('database_connection');//create a connection with your DB
$sql="SELECT * FROM (SELECT * FROM product WHERE car =? ORDER BY onSale DESC) AS product_ordered GROUP BY type"; //Your sql Query
$stmt = $conn->prepare($sql); // Prepare your sql
$stmt->bindValue(1, 'large'); // bind your values ,if you have to bind another value, you need to write $stmt->bindValue(2, 'anothervalue'); but your order is important so on..
$stmt->execute(); //execute your sql
$result=$stmt->fetchAll(); // fetch your result
happy coding

Resources