Laraver FindOrNew with multiple parameters - php

I'm using laravel FindOrNew() to get an entry with two parameters, or create a new one:
$option = \App\Option::findOrNew(['user_id' => $this->id , 'option_name' => $optionName]);
I want to get an option for a user that has the name in $optionName. The problem is that it just checks for the user_id, and does not create a new one when option_name does not exist.. instead it "finds" one which does not match the $optionName value..
Can someone say what I'm doing wrong? How can I achieve this?

TL;DR:
You're using the wrong method. You're looking for the firstOrNew() method, not findOrNew().
Explanation:
The findOrNew() is an extension of the find() method, which works on ids only. It takes two parameters, the first being the id (or array of ids) to find, and the second being the columns to retrieve. It's treating the array you've passed in as an array of ids to find.
The firstOrNew() method takes one parameter: an array of attributes to search for. It will turn the array into a where clause, and then call first() on the query builder. If no results are returned, it returns a new instance with those attributes filled in.

Related

How to query row with any value from a parameter array matching any value from a doctrine array

I've got an entity with a Doctrine column DC2TYPE fake array.
I would like to create a query fetching any result from this table that got a match between any value of the parameter array, and the doctrine array.
The parameter array is just a classic numeric array.
I've tried things like this.
$queryBuilder->select('p.country')
->where('p.classification IN (:class)')
->setParameter('class',$class);
or with Member of syntax, or with like, or with putting %.
So far on stack overflow all the tips i've found were working with attributes of entities that were part of a join column, or there was need for one matching from parameter or one matching from the column.
May be this isn't possible?
The function in repo looks like something like this.
public function getCountCountryByClass(array $class,int $clientId){
$class4='G01N';
$queryBuilder= $this->createQueryBuilder('p');
$queryBuilder->select('p.country')
->where('p.classification IN (:class)')
->setParameter('class',$class);
}

Laravel convert resultset to array

Database table SITE has many columns. One of them is site_id. I need all the site_ids as an array since it has to be fed to a method which accepts only a string array.
What I tried so far is:
$sites = DB::select('select site_id from site_tab');
$sites_arr = $sites->toArray();
But this doesn't produce the result I want. I need $sites_arr to be like ['A','B','C',...]
Please suggest a way to get this done. A solution based on Eloquent is also OK for me.
Thanks
Try this:
DB::table('site_tab')->pluck('site_id')->toArray();
reference pluck
referen toArray
If you open a manual, you will see that
The select method will always return an array of results
So, there's no need to use ->toArray(), as result is already an array.
To get values as array of names you can do:
$site_ids = DB::table('site_tab')->pluck('site_id');
Using ->toArray() here is optional, as you can iterate over $site_ids (which is a Collection) with a foreach too.

Laravel get single column result as string

Hello I would like to know is it possible to get column value as string. Instead of array in array:
Current query: Number::limit('1000')->get(['number'])->toArray()
The result at the moment is this:
Preferable result:
Before your toArray() call, add pluck('number'):
$result = Number::limit('1000')->get(['number'])->pluck('number')->toArray();
That's it! This will pluck just the number attributes from your result collection, and give you a single-level array.
The reason this works, is because you are getting a Collection back from get():
All multi-result sets returned by Eloquent are an instance of the Illuminate\Database\Eloquent\Collection object, including results retrieved via the get method or accessed via a relationship.
And the pluck method:
https://laravel.com/docs/5.1/collections#method-pluck
Update
Another, even more succinct method provided by #wunch in the comments:
$result = Number::limit('1000')->lists('number')->toArray();

YiiMongodbSuite count doesnt work

I'm lost at this point.
Here is what i have:
$criteria = new \EMongoCriteria();
$criteria->userId = new \MongoID($userId);
$criteria->expiresAt = array('>' => new \MongoDate(time()));
Then I'm running this:
$model->count($criteria);
And it always returns 0 when i know that there are documents that meet this criteria.
Any ideas?
UPDATE
findAllByAttributes() with the same criteria works perfectly. But I don't need those documents i need to count them.
When setting criteria field as property it uses simple comparision (field == value). You should set this criteria by calling field, like that:
$criteria->expiresAt('>', new \MongoDate(time()));
NOTE: Passing criteria to findAllByAttributes in wrong, it is not intended to work with EMongoCriteria, but with simple array. If you want to use criteria object pass it to findAll method.

Count on Zend_Db_Select

Say I have a random zend_db_select object.
How can I perform a count on that object, so I know the amount of items that meet the query.
I tried the following:
$data->TotalRecords = $select->columns(new Zend_Db_Expr('COUNT(*)'))->query()->fetch();
But this gives me the following error:
Message: No table has been specifiedfor the FROM clause
The query by itself works fine and returns a resultset.
There's a couple of ways of specifying the columns to fetch in a Zend_Db_Select. The following two product the same SQL
$select = $db->select()
->from('myTable', array())
->columns(array('TotalRecords' => new Zend_Db_Expr('COUNT(*)')));
$select = $db->select()
->from('myTable', array('TotalRecords' => new Zend_Db_Expr('COUNT(*)')));
The from method takes a first argument, the table name, and a second argument, an array of columns to fetch. If you're using an expression, you can specify a 'key' => Expr.
It's really easy to convert a Zend_Db_Select into a SQL string for debugging or use with other functions.
echo $select; // prints SELECT COUNT(*) AS `TotalRecords` FROM `myTable`
This uses a toString method, which is called automatically by Zend_Db fetch methods:
$total = $db->fetchOne($select);
echo $total; //prints the number of rows matching the query
Where $db is an instance of Zend_Db.
Use $select->__toString() method to output your generated query and see what is wrong with it.
If u dont have a from clause in your query add From() method to your select object.
If you use Zend_Db_Select, you have to call the from method to set the table name. With a Zend_Db_Table_Select, the table is passed in the constructor, so you don't need to call from.
$select = $db->select();
$select->from(
'table_name',
array('cnt' => 'count(1)')
);
I just encountered the same issue and found out what is going wrong
the Zend_Db_Select::columns functions expects an Array instead of a Object or String (when the first parameter is an String or Object it'll probably use this as main table for the columns you give but Im not sure about that.).
Changing your code to
$data->TotalRecords = $select->columns(array(new Zend_Db_Expr('COUNT(*)')))->query()->fetch();
Will fix your issue

Categories