Better way to increment +1 in laravel query? - mysql

I want to increment +1 the value i get with the query.
The query is this:
$project->order = DB::table('projects')
->where('order', DB::raw( "( select max(`order`) from projects )" ))
->get();
I think i should do something with increment, or just put +1 in the query, but not.
What's the better way to do it?
Thanks !

Try this :
$project->order = DB::table('projects')
->where('order', DB::raw("(select max(`order`) from projects)"))
->first()
->order + 1;

Related

Codeigniter join, group by and count a row from one table

I'm struggling a bit with this code to get the count result from book_listing (totally) which is the total count of bookings. From the result, some are correct but some are multiplied by 3 or so.
Here is my code:
$this->db->where('list_status', 1)
->where('list_date >=', date('Y-m-d'))
->order_by("user_listings.list_created", "desc")
->limit(18, null)
->select('*, COUNT(user_bookings.book_listing) as totally')
->from('user_listings')
->join('user_images', 'user_images.img_listing = user_listings.list_reference')
->join('user_states', 'user_states.state_id = user_listings.list_state')
->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
->group_by('user_listings.list_reference')
->get();
Thanks to any help :)
So I solved it, the user_images table seems to be causing the issue due to multiple images being fetched while I need it to return only one.
$this->db->where('list_status', 1)
->where('list_date >=', date('Y-m-d'))
->order_by("user_listings.list_created", "desc")
->limit(18, null)
->select('user_listings.*,image.*,user_states.*')
->select('COUNT(user_bookings.book_listing) as totalBooked')
->from('user_listings')
->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
->join('(SELECT * FROM user_images WHERE user_images.img_key IN(SELECT MIN(user_images.img_key) FROM user_images GROUP BY user_images.img_listing)) AS image',
'image.img_listing = user_listings.list_reference')
->join('user_states', 'user_states.state_id = user_listings.list_state')
->group_by('user_listings.list_reference')
->get();
Basically, I had to do a select from the join table for user_images. Hope it helps someone else :)

How to convert RIGHT LEFT functions to codeigniter active record

I have a query like this:
SELECT RIGHT(id, 1) id_root
FROM user
WHERE LENGTH(id) = 3
and LEFT(id, 1) = '0'
And how to convert that's query to active record in codeigniter.
My problem is with syntax RIGHT( id, 1 ) and also at LEFT(id,1)='0'
$result_arr = $this->db
->select("RIGHT(id, 1) id_root", FALSE)
->from("user")
->where(
array("LENGTH(id)"=> 3, "LEFT(id, 1) =" => 0)
)->get()
->result_array();
Or you can simply use $this->db->query("You SQL");
$query = "SELECT RIGHT(id, 1) id_root
FROM user
WHERE LENGTH(id) = ?
and LEFT(id, 1) = ? ";
$result_arr = $this->db->query($query, array(3, 0))->result_array();
You can produce your query like this
$this->db->from('user');
$this->db->select('RIGHT(id, 1) id_root',false);
$this->db->where('LENGTH(id)',3,true);
$this->db->where('LEFT(id, 1) =','0',true);
$results=$this->db->get()->result();
Remember if you want to use mysql function at your select query which may break mysql syntax by codeigniter use false as 2nd parameter so that codeigniter does not protect/covert your fields.
Same for where, if you want to use mysql function or other function which may break mysql syntax by CI use 3rd parameter as true so that codeigniter does not convert your fields.
See details at documentation
Simplest way to get any query result using $this->db->query('YOUR_QUERY') But I prefer using CI Active record's functions.
$query = "SELECT RIGHT(id, 1) id_root
FROM user
WHERE LENGTH(id) = 3
and LEFT(id, 1) = '0'";
$result = $this->db->query($query);

Laravel 4 - SQL query to Laravel Eloquent query

I'm working on a school project and I'm trying to get a query working.
SELECT *
FROM `ziekmeldingen` AS a
WHERE NOT EXISTS
(SELECT *
FROM `ziekmeldingen` AS b
WHERE `ziek` = 1
AND a.personell_id = b.personell_id)
Name of the model: ZiekmeldingenModel
I tried 2 things, both dont work ->
$medewerkers = ZiekmeldingenModel::whereNotExists(function($query)
{
$query->select()->from('ziekmeldingen AS b')->where('ziek', '=', '1')->where('ziekmeldingen.personell_id', '=', 'b.personell_id');
})->get();
return $medewerkers;
And
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->get();
Both of them give back all the results from the table while it should only give back 1 result (I've tested the original query, it works).
EDIT: Forgot to mention I'm using relationships in the model. So the raw solution probably won't work anyway
Found the answer. Had to use a combo of both the things I tried.
$medewerkers = ZiekmeldingenModel::select()
->from(DB::raw('`ziekmeldingen` AS a'))
->whereNotExists(function($query){
$query->select()
->from(DB::raw('`ziekmeldingen` AS b'))
->whereRaw('`ziek` = 1 AND a.personell_id = b.personell_id');
})->get();
return $medewerkers;
Thanks for any help and effort.
Definitely no need for select(). Also no raw in from or whereRaw needed.
The only unusual thing here is raw piece in the where, since you don't want table.field to be bound and treated as string. Also, you can use whereRaw for the whole clause in case you have your tables prefixed, otherwise you would end up with something like DB_PREFIX_a.personell_id, so obviously wrong.
This is how you do it:
$medewerkers = ZiekmeldingenModel::from('ziekmeldingen AS a')
->whereNotExists(function ($q) {
$q->from('ziekmeldingen AS b')
->where('ziek', 1)
->where('a.personell_id', DB::raw('b.personell_id'))
// or:
// ->whereRaw('a.personell_id = b.personell_id');
})->get();
Use the take() method though if you're not ordering your results the record you get back could be any of the results.
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->take(1)->get();

Converting MYSQL to Codeigniter

I am trying to convert a MYSQL query to codeigniter and going no wheres real fast. I am trying to convert this query
$conn->prepare("SELECT `id`,`song`,`artist`,`album`,`track`,`mix_name`,`date` FROM `podcasts` where mix_number = (SELECT MAX(mix_number) FROM podcasts) order by track asc");
This is in my model:
//$where = '(SELECT MAX(mix_number)from podcasts)';
$this->db->select('id,song,artist,album,track,mix_name,date, link');
//$this->db->where('mix_number', '(SELECT MAX(mix_number)from podcasts)');
$this->db->order_by('track', 'asc');
$query = $this->db->get('podcasts');
return $query->result();
My problem area is in the where statement. When I comment out the where statement I get the data. Obviously not in the manner I want it.
I am doing it this way becuase my next query(s) will be
("SELECT `id`,`song`,`artist`,`album`,`track`,`mix_name`,`date` FROM `podcasts` where mix_number = **(SELECT MAX(mix_number) FROM podcasts) - 1** order by track asc")
And on down to (SELECT MAX(mix_number) FROM podcasts) - 3
Any thoughts on the proper way of writing the where statement? Thank you for yout time.
Set the third argument of where() to false to prevent CI from altering the string you pass in to the second argument, then you can do the subquery:
return $this->db
->select('id,song,artist,album,track,mix_name,date, link')
->where('mix_number', '(SELECT MAX(mix_number) from podcasts)', false)
->order_by('track', 'asc')
->get('podcasts')
->result();
https://www.codeigniter.com/userguide2/database/active_record.html$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.
For me this produces the following query:
SELECT `id`, `song`, `artist`, `album`, `track`, `mix_name`, `date`, `link`
FROM (`podcasts`)
WHERE mix_number = (SELECT MAX(mix_number) from podcasts) ORDER BY `track` asc
If you are not too particular about using CodeIgniter's Active Record syntax, you can simply use your query as is:
$sql = "SELECT `id`,`song`,`artist`,`album`,`track`,`mix_name`,`date` FROM `podcasts` where mix_number = (SELECT MAX(mix_number) FROM podcasts) order by track asc";
$this->db->query($sql);
and then use $query->result() to get your results.

Doctrine Query whereIn and orWhere

My query is this :
$q = Doctrine_Query::create()
->from('plans p')
->whereIn('c.centerid',$centers)
->andWhere('p.agecategory = ?', $ageType)
->andWhere('p.type = ?', '2')
->andWhere('p.active = ?', '1')
->leftJoin('p.plansCenters c');
return $q->execute();
I wont to add one more row :
orWhere('p.allcenters =?' , '1')
Problem is this :
I wont to remove this whereIn clouse if c.allcenters =? 1 and oposit if c.allcenters =? 0 to show query whit whereIn clouse. If i wrhite orWhere after WhereIn clouse this 3 andWhere after this dont work Please help :)
I didn't fully understand the problem but I am familiar with complex orWhere/andWhere clauses. You have to use combined where conditions likes this:
->where("q.column=? AND w.column=?", ...)
->orWhere("e.id=? AND r.name=?", ....)
->orWhere("t.id=? AND (y.id=? OR u.id=?)", ...)
I hope you understand the idea, this is perfectly legit way.