I want to apply a where condition to relation. Here's what I do:
Replay::whereHas('players', function ($query) {
$query->where('battletag_name', 'test');
})->limit(100);
It generates the following query:
select * from `replays`
where exists (
select * from `players`
where `replays`.`id` = `players`.`replay_id`
and `battletag_name` = 'test')
order by `id` asc
limit 100;
Which executes in 70 seconds. If I manually rewrite query like this:
select * from `replays`
where id in (
select replay_id from `players`
where `battletag_name` = 'test')
order by `id` asc
limit 100;
It executes in 0.4 seconds. Why where exists is the default behavior if it's so slow? Is there a way to generate the correct where in query with query builder or do I need to inject raw SQL? Maybe I'm doing something wrong altogether?
replays table has 4M rows, players has 40M rows, all relevant columns are indexed, dataset doesn't fit into MySQL server memory.
Update: found that the correct query can be generated as:
Replay::whereIn('id', function ($query) {
$query->select('replay_id')->from('players')->where('battletag_name', 'test');
})->limit(100);
Still have a question why exists performs so poorly and why it is the default behavior
Try this:
mpyw/eloquent-has-by-non-dependent-subquery: Convert has() and whereHas() constraints to non-dependent subqueries.
mpyw/eloquent-has-by-join: Convert has() and whereHas() constraints to join() ones for single-result relations.
Replay::hasByNonDependentSubquery('players', function ($query) {
$query->where('battletag_name', 'test');
})->limit(100);
That's all. Happy Eloquent Life!
The reason for laravel has(whereHas) sometimes slowly is that implemented with where exists syntax.
For example:
// User hasMany Post
User::has('posts')->get();
// Sql: select * from `users` where exists (select * from `posts` where `users`.`id`=`posts`.`user_id`)
The 'exists' syntax is a loop to the external table, and then queries the internal table (subQuery) every time.
However, there will be performance problems when the users table has a large amount of data, because above sql select * from 'users' where exists... unable to use index.
It can use where in instead of where exists here without damaging the structure.
// select * from `users` where exists (select * from `posts` where `users`.`id`=`posts`.`user_id`)
// =>
// select * from `users` where `id` in (select `posts`.`user_id` from `posts`)
This will greatly improve performance!
I recommend you try this package hasin, in the above example, you can use the hasin instead of the has.
// User hasMany Post
User::hasin('posts')->get();
// Sql: select * from `users` where `id` in (select `posts`.`user_id` from `posts`)
The hasin just only use where in syntax instead of where exists compared with the framework has, but everywhere else is the same, such as parameters and call mode even the code implementation, and can be used safely.
whereHas performance is poor on tables without index, put index on it and be happy!
Schema::table('category_product', function (Blueprint $table) {
$table->index(['category_id', 'product_id']);
});
This is related to the mysql not to the laravel. You can perform the same thing you wanted from the above with the both options, joins and the subqueries. Subqueries are generally much slower than joins.
Subqueries are:
less complicated
elegant
easier to understand
easier to write
logic separation
and the above facts are why ORMs like eloquent are using suquries. but there are slower! Especially when you have many rows in the database.
Join version of your query is something like this :
select * from `replays`
join `players` on `replays`.`id` = `players`.`replay_id`
and `battletag_name` = 'test'
order by `id` asc
limit 100;
but now you must change select and add group by and be careful on many other things, but why is this so it is beyond that answer. New query would be :
select replays.* from `replays`
join `players` on `replays`.`id` = `players`.`replay_id`
and `battletag_name` = 'test'
order by `id` asc
group by replays.id
limit 100;
So that are the reasons why join in more complicated.
You can write raw query in laravel, but eloquent support for join queries are not well supported, also there are no much packages that can help you with that, this one is for example : https://github.com/fico7489/laravel-eloquent-join
WhereHas() query is really as slow as lazy turtle, so I created and still using a trait that I glue to any laravel model which required a simple join requests. This trait make a scope function whereJoin(). You can just pass there a joined model class name, where clause params and enjoy. This trait take care of table names and related details in query. Well, it's for my personal use and ofc feel free to modify this monstruosity.
<?php
namespace App\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
/** #mixin Model */
trait ModelJoinTrait
{
/**
* #param string|\Countable|array $on
* #param $column
* #param $whereOperator
* #param $value
* #param Model $exemplar
* #return array
*/
function _modelJoinTraitJoinPreset($on, $column, $whereOperator, $value, $exemplar){
$foreignTable = $exemplar->getTable();
$foreignId = $exemplar->getKeyName();
$localTable = $this->getTable();
$localId = $this->getKeyName();
//set up default join and condition parameters
$joinOn =[
'local' => $localTable.'.'.$localId,
'foreign'=> $foreignTable.'.'.$foreignId,
'operator' => '=',
'type'=>'inner',
'alias'=>'_joint_id',
'column'=>$column,
'where_operator'=>$whereOperator,
'value'=>$value
];
//config join parameters based on input
if(is_string($on)){
//if $on is string it treated as foreign key column name for join clause
$joinOn['foreign'] = $foreignTable.'.'.$on;
} elseif (is_countable($on)){
//if $is array or collection there can be join parameters
if(isset($on['local']) && $on['local'])
$joinOn['local'] = $localTable.'.'.$on['local'];
if(isset($on['foreign']) && $on['foreign'])
$joinOn['foreign'] = $localTable.'.'.$on['foreign'];
if(isset($on['operator']) && $on['operator'])
$joinOn['operator'] = $on['operator'];
if(isset($on['alias']) && $on['alias'])
$joinOn['alias'] = $on['alias'];
}
//define join type
$joinTypeArray = ['inner', 'left', 'right', 'cross'];
if(is_countable($on) && isset($on['type']) && in_array($on['type'], $joinTypeArray))
$joinOn = $on['type'];
return $joinOn;
}
/**
* #param Model $exemplar
* #param string|array|\Countable $joinedColumns
* #param string|array|\Countable $ownColumns
* #param string $jointIdAlias
* #return array
*/
function _modelJoinTraitSetColumns($exemplar, $joinedColumns, $ownColumns, $jointIdAlias = '_joint_id')
{
$foreignTable = $exemplar->getTable();
$foreignId = $exemplar->getKeyName();
$localTable = $this->getTable();
$localId = $this->getKeyName();
if(is_string($joinedColumns))
$foreignColumn = ["$foreignTable.$joinedColumns"];
else if(is_countable($joinedColumns)) {
$foreignColumn = array_map(function ($el) use ($foreignTable) {
return "$foreignTable.$el";
}, $joinedColumns);
} else {
$foreignColumn = ["$foreignTable.*"];
}
if(is_string($ownColumns))
$ownColumns = ["$localTable.$ownColumns"];
elseif(is_countable($ownColumns)) {
$ownColumns = array_map(function ($el) use ($localTable) {
return "$localTable.$el";
}, $ownColumns);
} else {
$ownColumns = ["$localTable.*"];
}
$columns = array_merge($foreignColumn, $ownColumns);
if($foreignId == $localId){
$columns = array_merge(["$foreignTable.$foreignId as $jointIdAlias"], $columns);
}
return $columns;
}
/**
* #param Builder $query
* #param string|array|\Countable $on
* #param Model $exemplar
*/
function _modelJoinTraitJoinPerform($query, $on, $exemplar){
$funcTable = ['left'=>'leftJoin', 'right'=>'rightJoin', 'cross'=>'crossJoin', 'inner'=>'join'];
$query->{$funcTable[$on['type']]}($exemplar->getTable(),
function(JoinClause $join) use ($exemplar, $on){
$this->_modelJoinTraitJoinCallback($join, $on);
}
);
}
function _modelJoinTraitJoinCallback(JoinClause $join, $on){
$query = $this->_modelJoinTraitJoinOn($join, $on);
$column = $on['column'];
$operator = $on['where_operator'];
$value = $on['value'];
if(is_string($column))
$query->where($column, $operator, $value);
else if(is_callable($column))
$query->where($column);
}
/**
* #param JoinClause $join
* #param array|\Countable $on
* #return JoinClause
*/
function _modelJoinTraitJoinOn(JoinClause $join, $on){
//execute join query on given parameters
return $join->on($on['local'], $on['operator'], $on['foreign']);
}
/**
* A scope function used on Eloquent models for inner join of another model. After connecting trait in target class
* just use it as ModelClass::query()->whereJoin(...). This query function forces a select() function with
* parameters $joinedColumns and $ownColumns for preventing overwrite primary key on resulting model.
* Columns of base and joined models with same name will be overwritten by base model
*
* #param Builder $query Query given by Eloquent mechanism. It's not exists in
* ModelClass::query()->whereJoin(...) function.
* #param string $class Fully-qualified class name of joined model. Should be descendant of
* Illuminate\Database\Eloquent\Model class.
* #param string|array|\Countable $on Parameter that have join parameters. If it is string, it should be foreign
* key in $class model. If it's an array or Eloquent collection, it can have five elements: 'local' - local key
* in base model, 'foreign' - foreign key in joined $class model (default values - names of respective primary keys),
* 'operator' = comparison operator ('=' by default), 'type' - 'inner', 'left', 'right' and 'cross'
* ('inner' by default) and 'alias' - alias for primary key from joined model if key name is same with key name in
* base model (by default '_joint_id')
* #param Closure|string $column Default Eloquent model::where(...) parameter that will be applied to joined model.
* #param null $operator Default Eloquent model::where(...) parameter that will be applied to joined model.
* #param null $value Default Eloquent model::where(...) parameter that will be applied to joined model.
* #param string[] $joinedColumns Columns from joined model that will be joined to resulting model
* #param string[] $ownColumns Columns from base model that will be included in resulting model
* #return Builder
* #throws \Exception
*/
public function scopeWhereJoin($query, $class, $on, $column, $operator = null, $value=null,
$joinedColumns=['*'], $ownColumns=['*']){
//try to get a fake model of class to get table name and primary key name
/** #var Model $exemplar */
try {
$exemplar = new $class;
} catch (\Exception $ex){
throw new \Exception("Cannot take out data of '$class'");
}
//preset join parameters and conditions
$joinOnArray = $this->_modelJoinTraitJoinPreset($on, $column, $operator, $value, $exemplar);
//set joined and base model columns
$selectedColumns = $this->_modelJoinTraitSetColumns($exemplar, $joinedColumns, $ownColumns, $joinOnArray['alias']);
$query->select($selectedColumns);
//perform join with set parameters;
$this->_modelJoinTraitJoinPerform($query, $joinOnArray, $exemplar);
return $query;
}
}
You can use it like this (Model Goods in example have a dedicated extended data model GoodsData with hasOne relationship between them):
$q = Goods::query();
$q->whereJoin(GoodsData::class, 'goods_id',
function ($q){ //where clause callback
$q->where('recommend', 1);
}
);
//same as previous exmple
$q->whereJoin(GoodsData::class, 'goods_id',
'recommend', 1); //where clause params
// there we have sorted columns from GoodsData model
$q->whereJoin(GoodsData::class, 'goods_id',
'recommend', 1, null, //where clause params
['recommend', 'discount']); //selected columns
//and there - sorted columns from Goods model
$q->whereJoin(GoodsData::class, 'goods_id',
'recommend', '=', 1, //where clause params
['id', 'recommend'], ['id', 'name', 'price']); //selected columns from
//joined and base model
//a bit more complex example but still same. Table names is resolved
//by trait from relevant models
$joinData = [
'type'=>'inner' // inner join `goods_data` on
'local'=>'id', // `goods`.`id`
'operator'=>'=' // =
'foreign'=>'goods_id', // `goods_data`.`goods_id`
];
$q->whereJoin(GoodsData::class, $joinData,
'recommend', '=', 1, //where clause params
['id', 'recommend'], ['id', 'name', 'price']); //selected columns
return $q->get();
Resulting SQL query will be like this
select
`goods_data`.`id` as `_joint_id`, `goods_data`.`id`, `goods_data`.`recommend`,
`goods`.`id`, `goods`.`name`, `goods`.`price` from `goods`
inner join
`goods_data`
on
`goods`.`id` = `goods_data`.`goods_id`
and
-- If callback used then this block will be a nested where clause
-- enclosed in parenthesis
(`recommend` = ? )
-- If used scalar parameters result will be like this
`recommend` = ?
-- so if you have complex queries use a callback for convenience
In your case there should be like this
$q = Replay::query();
$q->whereJoin(Player::class, 'replay_id', 'battletag_name', 'test');
//or
$q->whereJoin(Player::class, 'replay_id',
function ($q){
$q->where('battletag_name', 'test');
}
);
$q->limit(100);
To use it more efficiently, you can go like this:
// Goods.php
class Goods extends Model {
use ModelJoinTrait;
//
public function scopeWhereData($query, $column, $operator = null,
$value = null, $joinedColumns = ['*'], $ownColumns = ['*'])
{
return $query->whereJoin(
GoodsData::class, 'goods_id',
$column, $operator, $value,
$joinedColumns, $ownColumns);
}
}
// -------
// any.php
$query = Goods::whereData('goods_data_column', 1)->get();
PS I dont run any automated tests for this so be careful in use. It works just fine in my case, but there may be unexpected behaviour in yours.
I think performance does not depend on whereHas only it depends on how many records you have selected
Plus try to optimize your mysql server
https://dev.mysql.com/doc/refman/5.7/en/optimize-overview.html
and also Optimize your php server
and if you have faster query why don't you use raw query object from larval
$replay = DB::select('select * from replays where id in (
select replay_id from players where battletag_name = ?)
order by id asc limit 100', ['test']
);
You can use left join
$replies = Replay::orderBy('replays.id')
->leftJoin('players', function ($join) {
$join->on('replays.id', '=', 'players.replay_id');
})
->take(100)
->get();
I have sql condidtion SELECT * FROM (SELECT * FROM Prices WHERE aliasId = :aliasId order by id desc) p1 group by p1.currency and I am trying to use it in hasMany statement.
$q = $this->hasMany(Prices::className(), ['aliasId' => 'id']);
$db = \Yii::$app->db;
$query = $db
->createCommand('SELECT * FROM (SELECT * FROM Prices WHERE aliasId = :aliasId order by id desc) p1 group by p1.currency')
->bindValue(':aliasId', $this->id);
$query->prepare(true);
$q->sql = $query->getRawSql();
return $q;
But $this->id is empty when hasMany calling. Is there any way to bind custom query and link array there?
UPDATE.
I know that the reason of $this->id is empty, because I'm using Prices::find()>with('prices') in my Controller, so Yii creates query for all prices list. hasMany just adds addWhere('in', $key, $value) in empty query from $link parameter, I'm trying to override his query, but I can't.
$this->id is empty for new PriceAlias instances, and it's filled only after the model is saved in db - you are getting an empty value most likely because getPrices() is called before the model is saved in db.
You can test if $this->id != null or $this->isNewRecord == false before building the custom command, otherwise return null, an empty array or as required.
UPDATE 1: not sure I fully understand your update,
Prices::find()>with('prices') does create a WHERE ... IN (...) query, but
hasMany does not add an addWhere rule, it creates a relation for the ActiveRecord class. In your case:
$this->hasMany(Prices::className(), ['aliasId' => 'id'])
// generates: SELECT * FROM `prices` WHERE `aliasId` = :id
And the query is executed only when you specifically call getPrices() for an object.
So your problem is? after $q->sql = $query->getRawSql(); statement, $q->sql is not SELECT * FROM (SELECT * FROM Prices WHERE aliasId = :aliasId order by id desc) p1 group by p1.currency ?
UPDATE 2: I understand now. I can't think of any way of using Prices::find()->with() on relations with custom sql, at least not as the one you would like to use.
I can only suggest to find an alternative to find()->with() in your controller if you need to keep the custom query.
From official doc:
$subQuery = (new Query())->select('id')->from('user')->where('status=1');
// SELECT * FROM (SELECT `id` FROM `user` WHERE status=1) u
$query->from(['u' => $subQuery]);
In your case it should be something like this:
$subQuery = (new Query())->select('*')->from('Prices')->where('aliasId = :aliasId', ['aliasId'=>$aliasId])->orderBy('id');
$query->from(['p1' => $subQuery])->groupBy('p1.currency');
My model:
public function getSolServicoById($id){
$select = 'SELECT * FROM solicitacao_servico WHERE id_solicitacao = "$id" LIMIT 1';
$query = $this->db->query($select);
return $query->result();
}
My controller:
public function editaSolicitacao($id){
$this->load->model('Pedido_Model','pedido');
echo $id;
$data = $this->pedido->getSolServicoById($id);
print_r($data);
}
When i select it on database i receive rows but when i select in application i get empty array and i don't know why it happen?!
Try this :
$select = "SELECT * FROM solicitacao_servico WHERE id_solicitacao = '{$id}' LIMIT 1";
Also look forward to using prepared statements to reduce sql-injection vulnerability.
A better way to do this, just because its a simple query in CI is:
$this->db
->select('*')
->from('solicitacao_servico')
->where('id_solicitacao',$id)
->limit(1)
->get();
Doing it this way doesn't constrain your code to a particular database type (MySQL, MSSQL, etc) because it will create the correct syntax for your application with the built in active record feature.
I am developing with symfony 1.4 and using Doctrine ORM.
After building schema and models i've got some classes for work with database. I can also use Doctrine_query .... The only thing, that i cann`t understend is:
I need to update table.
Doctrine_Query::create()->update('table')->.....->execute().
or
$tbl = new Table();
$tbl->assignIdentifier($id);
if($tbl->load()){
$tbl->setFieldname('value');
$tbl->save();
}
how can i understend was it successful result of query or not ? and how much rows was updated.
p.s. the same question is for delete operation.
Everything is in the doc for update and delete.
When executing DQL UPDATE and DELETE queries the executing of a query returns the number of affected rows.
See examples:
$q = Doctrine_Query::create()
->update('Account')
->set('amount', 'amount + 200')
->where('id > 200');
$rows = $q->execute();
echo $rows;
$q = Doctrine_Query::create()
->delete('Account a')
->where('a.id > 3');
$rows = $q->execute();
echo $rows;
This is related to DQL (when you are using doctrine queries). But I think ->save() will return the current object or true/false as #PLB commented.
$statement = $this->entityManager->getConnection()->prepare($sql);
$statement->execute();
// the counter of rows which are updated
$counter = $statement->rowCount();
It works for me very well with doctrine 2 in symfony 2 project
$nrRows = $this->getEntityManager()->getConnection()->executeUpdate('UPDATE ...');
The documentation for executeUpdate:
/**
* Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
* and returns the number of affected rows.
*
* This method supports PDO binding types as well as DBAL mapping types.
*
* #param string $query The SQL query.
* #param mixed[] $params The query parameters.
* #param int[]|string[] $types The parameter types.
*
* #return int The number of affected rows.
*
* #throws DBALException
*/
public function executeUpdate($query, array $params = [], array $types = [])
The following code is issuing the following error message:
A Database Error Occurred
Error Number: 1066
Not unique table/alias: 'users'
SELECT * FROM (`users`, `users`) JOIN `user_profiles` ON `users`.`id` = `user_profiles`.`user_id`
Filename: /home/xtremer/public_html/kowmanager/models/cpanel/dashboard.php
Line Number: 38
Here is my code:
class Dashboard extends CI_Model {
private $table_name = 'users'; // user accounts
private $profile_table_name = 'user_profiles'; // user profiles
function __construct() {
parent::__construct();
$ci =& get_instance();
$this->table_name = $ci->config->item('db_table_prefix', 'tank_auth').$this->table_name;
$this->profile_table_name = $ci->config->item('db_table_prefix', 'tank_auth').$this->profile_table_name;
}
/**
* Get user info by Id
*
* #param int
* #param bool
* #return object
*/
function get_user_info($id) {
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_profiles', 'users.id = user_profiles.user_id');
$query = $this->db->get($this->table_name);
if ($query->num_rows() == 1) {
return $data = $query->row();
} else {
return NULL;
}
}
}
EDIT: I know have this for my function and changed it because after looking at it I didn't need the extra table. I have an array ($data) of values being sent to my header but can I get away with sending it to the build that way it sends the array to all the partials.
function get_user_info($id)
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('users.id', $id);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $data = $query->row();
}
else
{
return NULL;
}
}
And this is from my controller I updated:
function index()
{
$id = $this->tank_auth->get_user_id();
$data = $this->Dashboard->get_user_info($id);
print_r($data);
$this->template->set_layout('cpanel')->enable_parser(false);
$this->template->set_partial('header', 'partials/header', $data);
$this->template->set_partial('sidebar', 'partials/sidebar');
$this->template->set_partial('content', 'partials/content');
$this->template->set_partial('footer', 'partials/footer');
$this->template->build('/cpanel/index');
}
The problem is this:
SELECT * FROM (users, users)
I assume you're trying to join the table to itself, but you can't do that without giving aliases to the tables, otherwise the database doesn't know which side of the join you're referring to when you reference fields from it.
Try this:
SELECT *
FROM users u1, users u2
JOIN user_profiles ON u1.id = user_profiles.user_id
Update:
My above answer was written based on the error message, but I didn't notice the code link (I've since added the code to be inline with the question).
I'm not overly familiar with CI, but I have a feeling your problem lies in these three lines:
private $table_name = 'users';
$this->db->from('users');
$query = $this->db->get($this->table_name);
In line 3, you're explicitly getting $this->table_name which points to the users table as shown in line 1). However, by explicitly setting a from table, also pointed to users, in line 2, I think you're accidentally setting up a join between two tables. Since these two tables are both the same, and neither is aliased, it is resulting in an error. Try removing the $this->db->from('users'); line and seeing if that resolves the issue.
Update 2:
I've been reading the CodeIgniter user guide, and it seems you don't need to specify anything as a parameter to $this->db->get() when you're using building a query using methods like from(). I'd suggest just changing this line:
$query = $this->db->get($this->table_name);
to this:
$query = $this->db->get();
See this page for details.
You are taking the Cartesian product of the users table with itself when you write users,users but not giving either of them an alias. I don't think you mean to be taking the Cartesian product at all. Try:
SELECT * FROM users JOIN user_profiles ON users.id = user_profiles.user_id