cakephp3 clause where doesn't work - cakephp-3.0

the code below is executed but it brings a wrong records(all records in my table) , it's like he doesn't take on consideration the clause where
$result = $this->Posts->query('SELECT * FROM POSTS WHERE id=1');
I know that I can do it easily with find() but for some reasons I want to write the sql statement and to have the right results
Thanks for helping me.

query() method does not take any parameter. you can use it like
$data= $this->Posts->query()
->where(['id'=>1])
->execute()
->fetchAll();

Related

how to search by letter in column in database (laravel)

I want to find by letter customer's first_name on my 'customers' table.
And the only thing that I get is an empty array.
For instance, I put in the parameter 'q' value 'E' to get customer Elena from my database by I get an only empty array.
I use the following code to get first_name :
$search = Input::get('q');
if($search)
{
$customers = Customer::all()->where('full_name', 'LIKE', "%{$search}%");
return ($customers);
}
Can someone help me?
Your query don't work because you are calling the all() method before the where(). That's actually not wrong, but it have different behavior.
When you call all(), it actually does the SQL query. After that, any chained methods are being called into a Eloquent Collection class, and it also have a where method, but that's simpler since it runs on PHO instead of running on SQL.
Since the collection's where() method doesn't support LIKE operator, it's probably searching for a value that is exactly %E%.
Hope it can help you understanding why your query doesn't work as expected.
Try this
$customers = Customer::where('full_name', 'LIKE', "%{$search}%")->get();
Laravel Eloquent

Eloquent select statement based on a condition in another table

I have an laravel eloquent select statement which looks like this:
$test = Test::with(['a.b.companies']) .. and so on
Now, I want to return results for this query based on some company names in companies table.
I tried to write a where clause with various trial and errors but it doesn't work. I am new to laravel and mysql. Any help in the right direction will be good. thanks.
You may use where, for more reference : - Eloquent ORM
$test = Test::where('company_name1', '=', $company_name1)->orWhere('company_name2', '=', $company_name2)->get();

Eloquent count distinct returns wrong totals

i'm having an issue with how eloquent is formulation a query that i have no access to. When doing something like
$model->where('something')
->distinct()
->paginate();
eloquent runs a query to get the total count, and the query looks something like
select count(*) as aggregate from .....
The problem is that if you use distinct in the query, you want something like
select count(distinct id) as aggregate from .....
to get the correct total. Eloquent is not doing that though, thus returning wrong totals. The only way to get the distinct in count is to pass an argument through the query builder like so ->count('id') in which case it will add it. Problem is that this query is auto-generated and i have no control over it.
Is there a way to trick it into adding the distinct on the count query?
P.S Digging deep into the builders code we find an IF statement asking for a field on the count() method in order to add the distinct property to the count. Illuminate\Database\Query\Grammars\BaseGrammar#compileAggregate
if ($query->distinct && $column !== '*')
{
$column = 'distinct '.$column;
}
return 'select '.$aggregate['function'].'('.$column.') as aggregate';
P.S.1 I know that in SQL you could do a group by, but since i'm eager loading stuff it is not a good idea cause it will add a IN (number of id's found) to each of the other queries which slows things down significantly.
I faced the exact same problem and found two solutions:
The bad one:
$results = $model->groupBy('foo.id')->paginate();
It works but it will costs too much memory (and time) if you have a high number of rows (it was my case).
The better one:
$ids = $model->distinct()->pluck('foo.id');
$results = $query = $model->whereIn('foo.id', $ids)->paginate();
I tried this with 100k results, and had no problem at all.
This seems to be a wider problem, discussed here:
https://github.com/laravel/framework/issues/3191
https://github.com/laravel/framework/pull/4088
Untill the fixes are shipped with one of the next Laravel releases, you can always try using the raw expressions, like below (I didnt test it, but should work)
$stuff = $model->select(DB::raw('distinct id as did'))
->where('whatever','=','whateverelse')
->paginate();
Reference: http://laravel.com/docs/queries#raw-expressions
$model->where('something')->distinct()->count('id')->paginate();

Yii activerecord and pagination count() slow query

So basicly the problem is in query SELECT COUNT(*) which executed in calculateTotalItemCount function in activedataprovider. As i understood it needed for pagination for $itemcount variable. The problem is this query slow for big tables. For my ~30m table it executes 5 seconds.
So there are 2 ways to solve this problem:
1. Disable pagination ('pagination'=>'false') and write own pagination.
2. Rewrite AR count function.
I dont have enough experience/knowledge to acomplish this.
Maybe some one had same issues before and can share his solution.
Atleast for totalItemCount we can use EXPLAIN SELECT *. Its way more faster.
I appreciate any help. Thank you.
If you have a "cheaper" query in raw SQL than the one that active records create automatically, you can also query manually (e.g. through DAO) and set the totalItemCount on your data provider:
$count = Yii::app()->db->createCommand('SELECT COUNT(*)...')->queryScalar();
$provider = new CActiveDataProvider('SomeModel', array(
'totalItemCount' => $count,
'criteria' => $criteria,
...

Using a table-alias in Kohana queries?

I'm trying to run a simple query with $this->db in Kohana, but am running into some syntax issues when I try to use an alias for a table within my query:
$result = $this->db
->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
->from("chapter_info ci")
->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
->get();
It seems to me that this should work just fine. I'm stating that "chapter_info" ought to be known as "ci," yet this isn't taking for some reason. The error is pretty straight-forward:
There was an SQL error: Table 'gb_data.chapter_info ci' doesn't exist -
SELECT `ci`.`chapter_id`, `ci`.`book_id`, `ci`.`chapter_heading`,
`ci`.`chapter_number`
FROM (`chapter_info ci`)
WHERE `ci`.`chapter_number` = 1
AND `ci`.`book_id` = 1
If I use the full table name, rather than an alias, I get the expected results without error. This requires me to write much more verbose queries, which isn't ideal.
Is there some way to use shorter names for tables within Kohana's query-builder?
In Kohana 3 it is simply enough:
->from( array('table_name', 'alias') )
and this will create the query that contains:
FROM 'table_name' AS 'alias'
I have tested it and it works. Good luck.
$result = $this->db
->select("ci.chapter_id, ci.book_id, ci.chapter_heading, ci.chapter_number")
->from("'chapter_info' AS ci")
->where(array("ci.chapter_number" => $chapter, "ci.book_id" => $book))
->get();
That should work. As you must wrap the original table name in quotes first before the AS keyword and the new table name you want to shorten it to.
Try using the "as" keyword like ->from("chapter_info as ci"), maybe the query builder will recognize it this way.