Yii2 subquery GROUP BY in active record - activerecord

can I convert this query
"SELECT * FROM (SELECT * FROM blog_post ORDER BY data DESC) blog_post GROUP BY blog_id LIMIT 2"
into a Yii2 active record query?
Thx
Ms

Yes, you can do this.
Yii2 gave us a wonderful library support.
You can form custom sql query and pass this query in findBySql() like:
$sql = "Some query/nested query";
$result = ModelClass::findBySql($sql);
Visit Yii official documentation.

BlogPost::find()
->orderBy('data DESC')
->groupBy('blog_id')
->limit(2)
->all();

I suppose you can do in this way :
Ⅰ:create a subQuery where you select from.
$blogPostQuery = BlogPostModel::find()->orderBy(['data' => SORT_DESC]);
Ⅱ:Get activeRecord results. The from params is an exist Query.
$models = (new yii\db\Query)
->from(['blog_post ' => $blogPostQuery])
->groupBy(['blog_id'])
->limit(2)
->all();
ps:
see yii\db\query->from()-detail in Yii Api;
(public $this from ( $tables )) $tables can be either a string (e.g. 'user') or an array (e.g. ['user', 'profile']) specifying one or several table names··· or a sub-query or DB expression
Have a try!I hope it`s useful for you:))

Related

how to union and groupby in laravel

i want to get contact id who was send chat or was i send chat to him
with native query i can get result but when i implement in laravel its going difficult
this my native query
select * from `users` where `users`.`id` in (
select `to` from messages where `from` = 2 group by `to`
union
select `from` from messages where `to` = 2 group by `from`
)
what i find difficult is how union after group by or group by after union with make same column number, i using merge but the result is wrong
this what i have try in laravel
$to = Message::select('to')->where('from',auth()->id())->groupBy('to')->get();
$from = Message::select('from')->where('to',auth()->id())->groupBy('from')->get();
$tofrom = $to->merge($from);
dd($tofrom);
please if any body can help
Unions are described in the documentation. To achieve your specific requirements you can do:
$final = User::whereIn('id', function ($query) {
$from = Message::select('from')->where('from',auth()->id())->groupBy('from');
$query->from('messages')->where('to',auth()->id())->groupBy('to')->union($from);
})->get();
Disclaimer: I have not actually tested this but I think it should work.
merge() is the method of collection. Not the Eloquent Builder or Query Builder.
However, It think you want to find user.id in the array.
You can convert the collection to array:
$to = Message::where('from',auth()->id())->groupBy('to')->pluck('to');
$from = Message::where('to',auth()->id())->groupBy('from')->pluck('from');
$tofrom = $to->merge($from)->toarray();
User::whereIn('id', $tofrom)->get();
oh finally i got the answer this is code
$contacts = User::select('users.id','users.name','users.email','users.profile_image')
->join('messages',function($join){
$join->on('users.id','messages.from');
$join->orOn('users.id','messages.to');
})
->where(function($query){
$query->where('messages.from',auth()->id())->orWhere('messages.to',auth()->id());
})
->groupBy('users.id','users.name','users.email','users.profile_image')
->get();

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.

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

Doctrine query only returning one row?

I'm new to Doctrine but somewhat familiar with SQL. I have a very simple schema with Users and Challenges. Each Challenge has a "challenger id" and a "opponent id" which are foreign keys into the User table. I want to print a list of all challenges, with the output being the names from the User table. Here is my Doctrine query;
$q = Doctrine_Query::create()
->select('u1.name challenger, u2.name opponent')
->from('Challenge c')
->leftJoin('c.Challenger u1')
->leftJoin('c.Opponent u2');
The problem is that this only returns one row. I've used the getSqlQuery() command to look at the generated SQL which ends up being:
SELECT u.name AS u__0, u2.name AS u2__1 FROM challenge c
LEFT JOIN user u ON c.challenger_id = u.id
LEFT JOIN user u2 ON c.opponent_id = u2.id
When run in a 3rd party SQL client this query retrieves all of the rows as expected. Any idea how I can get all of the rows from Doctrine? I'm using $q->execute() which I understand should work for multiple rows.
Thanks.
For me it worked by chaning the hydration mode:
$result = $query->execute(array(), Doctrine_Core::HYDRATE_SCALAR);
Set result set then returns an array instead of objects.
I just ran into this issue and in my case the problem was that my query didn't select any field from the FROM table. Example:
$query = Doctrine_Query::create()
->select(
'ghl.id as id,
ghl.patbase_id as patbase_id,
ghl.publication_no as publication_no,
ghl.priority_no as priority_no
'
)
->from('GridHitListContents ghlc')
->leftJoin('ghlc.GridHitList ghl')
As you can see there is no selected field from the GridHitListContents table.
with a $query->count() I got 2000ish results, but with $query->fetchArray() only the first one.
When I added
$query = Doctrine_Query::create()
->select(
'ghlc.id,
ghl.id as id,
...
'
)
->from('GridHitListContents ghlc')
->leftJoin('ghlc.GridHitList ghl')
I got back all my results.
$query->fetchOne() work fine for me.
Use this $result = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY)

Resources