Yii - How to use conditions like where and limit - activerecord

I use findAll() like this:
$l = SiteContentRelated::model()->findAll('content_1=:c', array(':c' => $id));
How I can add condition to this?
Like as LIMIT 5 or anything?

Use CDbCriteria to specify more detailed criteria:
$criteria = new CDbCriteria;
$criteria->condition = 'content_1=:c';
$criteria->limit = 5;
$criteria->params = array(':c' => $id);
$l = SiteContentRelated::model()->findAll($criteria);
or pass an array to findAll which will be converted to a CDbCriteria:
$l = SiteContentRelated::model()->findAll(array(
'condition' => 'content_1=:c',
'limit' => 5,
'params' => array(':c' => $id),
));
When you specify a LIMIT, it's a good idea to also specify ORDER BY.
For filtering based on model attributes, you can also use findAllByAttributes:
$l = SiteContentRelated::model()->findAllByAttributes(array(
'content_1' => $id,
), array(
'limit' => 5,
));

Related

create associative array with key and value generated in for

i´m traying to create associative array, from query in laravel.
public function assignAllCall(Request $request)
{
$callList = [];
$newCall = [];
for($i=0; $i<count($request->get('calls')); $i++){
array_push($callList, Listado::where('id', $request->get('calls')[$i])->get());
}
for($i=0; $i<count($callList); $i++){
for($j=$i; $j<count($callList[$i]); $j++){
$newCall = [
'nomape' => $callList[$i][$j]->nomape,
'direccion' => $callList[$i][$j]->direccion,
'provincia' => $callList[$i][$j]->provincia,
'ciudad' => $callList[$i][$j]->ciudad,
'cp' => $callList[$i][$j]->cp,
'telefono' => $callList[$i][$j]->telefono,
'movil' => $callList[$i][$j]->movil,
'id_teleoperadora' => $request->get('teleoperadora'),
'id_estado' => 1,
'fecha_asignacion' => Carbon::now()->format('Y-m-d H:m:s'),
'created_at' => Carbon::now()->format('Y-m-d H:m:s'),
];
}
print_r($newCall);
// create call
//$result = Llamada::create($newCall);
}
//return $result;
}
i have this function that receive param from ajax and this values it´s ids array.
I need get all data from this ids for get all data and create new calls with this data, for this i have one for to do query and assign to array. after i´m traying to create associative array but when i do print_r always i return same result:
Array
(
[nomape] => x
[direccion] => x
[provincia] => x
[ciudad] => x
[cp] => x
[telefono] => x
[movil] => x
[id_teleoperadora] => x
[id_estado] => x
[fecha_asignacion] => x
[created_at] => x
)
always same value. I don´t know if i do well my function or have one better solution for to do this.
Thanks for read and thanks for help.
Instead of
for($j=$i; $j<count($callList[$i]); $j++){
try this:
for($j=0; $j<count($callList[$i]); $j++){

Laravel5.5 adding columns to a collection from a second one

I have a sql request concerning admin :
$admin = Admin::findOrFail(Auth::guard('admin')->user()->id);
from this sql request I also manage to get the users of the admin ...
$users = $admin->users;
Each users must follow training sessions. and I must calculate it by using SQL requests for each users ... So i wrote this foreach statement
foreach ($users as $user) {
$todo = User::select() .....where('users.id' = $user->id)->get();
$done = User::select() .....where('users.id' = $user->id)->get();
$totalTimes = $todo->toBase()->sum('dureeformation');
$spendTimes = $done->toBase()->sum('dureeformation');
$remainingTimes = $totalTimes - $spendTimes;
$timeData[] = ['id' => $user->id, 'totalTime' => $totalTimes, 'spendTime' => $spendTimes, 'remainingTime' => $remainingTimes];
}
the totalTimes, spendTimes and remainingTimes are operations on Collections and i get expected results ...
$users->each(function ($record) use ($timeData) {
$record['totalTime'] = $timeData[$record['id']]['totalTime'];
$record['spendTime'] = $timeData[$record['id']]['spendTime'];
$record['remainingTime'] = $timeData[$record['id']]['remainingTime'];
//dd($record['totalTime']);
});
After this :
$timeData = collect($timeData);
$timeData= $timeData->keyBy('id');
$users = collect($users->toArray());
I have an issue here :
$users->each(function ($record) use ($timeData) {
$record['totalTime'] = $timeData[$record['id']]['totalTime'];
$record['spendTime'] = $timeData[$record['id']]['spendTime'];
$record['remainingTime'] = $timeData[$record['id']]['remainingTime'];
//var_dump($record);
});
$record in the function gives me what i expect ... the var_dump($records) added columns where it was expected but i can't take those results out of the function.
I tried to do this :
$variable = $users->each(function ($record) use ($timeData)...
dd($variable)
but unsuccessfully ...
Looks to me like your $timeData array is built differently than you access it. In your code you are doing
$timeData[] = [
'id' => $user->id,
'totalTime' => $totalTimes,
'spendTime' => $spendTimes,
'remainingTime' => $remainingTimes,
];
which will produce an array like this
[
0 => [
'id' => 17,
'totalTime' => 5,
'spendTime' => 4,
'remainingTime' => 3
],
1 => [
'id' => 17,
'totalTime' => 7,
'spendTime' => 5,
'remainingTime' => 2
]
]
but what you actually want is to have the id as index, right? Then you'd have to build the array this way:
$timeData[$user->id] = [
'totalTime' => $totalTimes,
'spendTime' => $spendTimes,
'remainingTime' => $remainingTimes,
];
or, as an alternative, perform a different lookup:
$users->each(function ($record) use ($timeData) {
$times = array_first($timeData, function ($value, $key) use ($record) {
return $value['id'] === $record['id'];
});
$record['totalTime'] = $times['totalTime'];
$record['spendTime'] = $times['spendTime'];
$record['remainingTime'] = $times['remainingTime'];
});
Both solutions have pros and cons, though. On the one hand, using the user identifier as the index will produce a huge array that is only filled partially. On the other hand, the second solution is a bit slower. As long as you are not going to deal with thousands of entries in the $timeData array, this won't be an issue, though.

insert method is overwriting what is in the cart and not adding to it

if($this->input->post('tambah')){
$kode = $this->input->post('kode');
$jumlah = $this->input->post('jumlah');
$hjual = $this->input->post('hjual');
$nama = $this->input->post('nama');
$exp = $this->input->post('tglexp');
$hpp = $this->input->post('hpp');
$temp_stok = $this->input->post('temp_stok');
$diskon = $this->input->post('diskon');
$cart = array(
'id' => $kode,
'qty' => $jumlah,
'price' => $hjual,
'name' => $nama,
'options' => array('exp' => $exp, 'hpp' => $hpp,
'temp_stok' => $temp_stok , 'diskon'=>$diskon ));
$this->cart->insert($cart);
header('location:'.base_url().'penjualan/load_input_barang_eceran');
}
I cant seem to add any more items and the latest one I add replaces the existing one.
I had like this in another controller but strangely can insert and not overwriting
I've had this.
It was non alphanumerics in the product code which caused the whole cart to behave strangely.
Try just having aaa123 etc as codes to test this

Laravel 4 - Return the id of the current insert

I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;

how to build fluent query by array of criterias in Laravel

If I store in DB criterias what I want to use to build and filter queries - how to build query with Laravel Fluent Query Builder? Maybe you can give advice for refactoring this array for adding OR/AND to make complex filter by such conditions? Thanks!
For example if I read from database these criteria and made array:
$array = array(
'0' => array(
'table' => 'users',
'column' => 'name',
'criteria' => 'LIKE'
'value' => 'John'
),
'1' => array(
'table' => 'groups',
'column' => 'name',
'criteria' => 'NOT LIKE'
'value' => 'Administrator'
),
...
)
If you are really set on doing it your way, make a switch statement to set the flag for the index of the array
switch ($query)
{
case 0:
$this->get_data($x);
break;
case 1:
$this->get_data($x);
break;
case 2:
$this->get_data($x);
break;
default:
Return FALSE;
}
public function get_data($x){
$value = DB::table($array[$x]['table'])
->where($array[$x]['name'], $array[$x]['criteria'], $array[$x]['value'])
->get();
Return $value;
}
However, I would not advise this at all. Instead of storing the query filters in an array I feel you should just make them methods in your model. This will help with readability, modularity, and having reusable code.
public function get_user_by_name($name){
$user = DB::table('users')->where('name', 'LIKE', '%'.$name.'%')->get();
return $user;
}
public function get_group_by_name($name, $criteria = 'LIKE'){
$groups = DB::table('groups')->where('name', $criteria, '%'.$name.'%')->get();
return $groups;
}
http://laravel.com/docs/database/fluent

Resources