Update table using custom queries in TYPO3 Extbase - php

I have a table named 'user'.I need to update the field 'email' .Is there any custom build queries for updating.I have only the uid of user.
I mean.. Is there any TYPO3 custom queries equivalent to
Update table 'user' set email = 'new#xyz.com' where uid = 1;
like
$query = $this->createQuery();
$query->matching(
$query->logicalAnd(
$query->equals('organization', $organization),
$query->contains('regions', $region)
)
)
return $query->execute();

if you use extbase , you can use :
$object = $this->yourRepository->yourQuery();
$object->setEmail('your#email.tld');
$this->yourRepository->update($object);

Why don't you use
use HDNET\ExtensionName\Utility;
Utility::exec_UPDATEquery (
$table,
$where,
$fields_values,
$no_quote_fields = false
);
Please refer exec_UPDATEquery From TYPO3

Related

Typo3 8.7.3 ExtBase - Individual MySQL Query in Repository

i am currently encounter a problem which is what i think connected to database cardinality and Typo3 not recognizing it.
I've got a project model which has different preevaluations, evaluations and mentorings connected with 1:n relationship. So i want to get all the projects where a user is connected to in either one of these models. The user for the different models can be different or the same, but i want to get the project only once back. Since i read in the documentation of the typo3 extbase, the cardinality is implicitly found by typo3 when i use individual db queries.
The evaluations, preevaluations and mentorings are set in the TCA with the type "inline" in a custom column declaration.
The function I am trying to use is that one over here:
public function findOwnedProjects($filters,$aSorting = NULL, $aSearch = NULL)
{
$user = $GLOBALS['TSFE']->fe_user->user;
$userId = $user['uid'];
$query = $this->createQuery();
$orCondition[] = $query->equals('preEvaluations.frontendUser', $userId);
$orCondition[] = $query->equals('evaluations.frontendUser', $userId);
$orCondition[] = $query->equals('mentorings.frontendUser', $userId);
$orCondition[] = $query->equals('projectlead', $userId);
$condition[] = $query->logicalOr($orCondition);
$condition[] = $query->equals("type", 'project', false);
$query->matching($query->logicalAnd($condition));
if (!empty($aSorting)) {
$sSorting = $aSorting['order'] == 'asc' ? \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_ASCENDING : \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING;
$sSortBy = strip_tags(trim($aSorting['sortBy']));
$query->setOrderings(array($sSortBy => $sSorting));
}
return $query->execute();
}
But this is returning duplicate projects when there is more than one preevaluation or so connected to the project. I tried var_dumping the SQL statement which is generated and could see there is no DISTINCT in use. That is the whole problem i think and i don't see a solution so far.
I am not a typo3 expert and just trying to figure out what the problem is. If you got any idea what i might have missed, please answer this question.
Thanks!
I would try with the $query->contains method like that :
$orCondition[] = $query->contains('preEvaluations.frontendUser', $userId);
$orCondition[] = $query->contains('evaluations.frontendUser', $userId);
$orCondition[] = $query->contains('mentorings.frontendUser', $userId);
$orCondition[] = $query->contains('projectlead', $userId);

How can I build a condition based query in Laravel using eloquent

I was wondering how can I build a condition based query in Laravel using eloquent?
I've found how to do it with a raw query but that that's not what I want also the answer to this question isn't that dynamic at least not as dynamic as I want it to be.
What I try to achieve is to create a dynamic WHERE query based on certain conditions, for example if the field is filled or not.
If I use the following code,
$matchThese = [
'role' => 'user',
'place' => \Input::get('location')
];
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();
The query will fail if I don't send a location as POST value. I don't want it to fail I want it to skip to the next WHERE clause in the query. So basically if there's no place given don't search for it.
Build up the query and include the ->where() clause depending on whether or not you have the location in your input:
$query = User::where('role', 'user');
$query = \Input::has('location') ? $query->where('location', \Input::get('location')) : $query;
$availableUsers = $query->take($count)->orderByRaw('RAND()')->get();
Just build the array with an if condition:
$matchThese = [
'role' => 'user',
];
if(\Input::has('location')){
$matchThese['place'] = \Input::get('location');
}
$availableUsers = User::where($matchThese)->take($count)->orderByRaw("RAND()")->get();
$query = DB::table('table_name');
if($something == "something"){
$query->where('something', 'something');
}
$some_variable= $query->where('published', 1)->get();
You can use something like this.

How can I get recent entris to first as deault in cakephp

i'm very new on cakephp.I have 35 tables in my data base and want to edit default index.ctp views to get recent entry first and also in other search results I want to put recent entries first. So, I'm try to edit find() function using 'beforeFind()' callback. I wrote following function and put it to 'AppController', but it didn't work. Is there any error in this code or I put it on wrong place.Does anyone help me to find mistake ? Thanks
function beforeFind($queryData) {
if (!isset($queryData['order'])) {
$queryData['order'] = array();
}
$queryData['order'][$model->alias.'.id'=> 'DESC'];
return $queryData;
}
Use cakephp model attribute
The default ordering of data for any find operation. Possible values include:
$order = "field"
$order = "Model.field";
$order = "Model.field asc";
$order = "Model.field ASC";
$order = "Model.field DESC";
$order = array("Model.field" => "asc", "Model.field2" => "DESC");
refer cakephp documentation
So in AppModel just define the following
public $order = "id desc";

Yii 1.x, query in query DB selection

I have such sql query
SELECT * FROM tbl_role WHERE
tbl_role.id NOT IN (
SELECT tbl_user_role.roleID FROM tbl_user_role
WHERE tbl_user_role.userID = 35
)
AND
tbl_role.id NOT IN (
SELECT tbl_user_role_request.roleID FROM tbl_user_role_request
WHERE tbl_user_role_request.userID = 35 AND tbl_user_role_request.dateEnd IS NULL)
What is the best solution to make it in Yii-like code. How can i do this query using Yii 1.x ?
Assumptions:
tbl_role has a model named Role
tbl_user_role has a model named UserRole
tbl_user_role_request has a model named UserRoleRequest
Note that this will do 3 seperate queries but I believe this is the closest you can get without creating a total mess.
<?php
$userId = 35;
$roles = UserRole::findAllByCondition(array('userId' => $userId));
$roleIds = array_values(CHtml::listData($roles, 'roleId', 'roleId');
$roleRequests = UserRoleRequest::findAllByCondition(array('userId'=>$userId, 'dateEnd'=>null));
$roleRequestIds = array_values(CHtml::listData($roleRequest, 'roleId', 'roleId'));
$criteria = new CDbCriteria();
$criteria->addNotInCondition('id', $roleIds);
$criteria->addNotInCondition('id', $roleRequestIds);
$roles = Role::findAll($criteria);
I would use CDbCommand: http://www.yiiframework.com/doc/api/1.1/CDbCommand#queryAll-detail
Use the following code to fetch the data
$data = Yii::app()->db->createCommand('sql query')->queryAll;
And then you can use this dataset to create the dropDownList
$list = CHtml::listData($data, 'value field', 'text field');
echo $form->dropDownList($model, 'attribute', $list);

How do I retrieve data in INT form from a database with codeigniter?

I am trying to create an update function that adds an entered value to the value for the user in a database. (It adds accounts that can be used for a class to a teacher) So far, I have a test button that should add one account when it's clicked and then refresh the page.
Here is my function thus far:
public function add_account()
{
$this->load->model("teacher_data_model");
$user = $this->ion_auth->user()->row();
$user_id = $user->id;
$data = array(
'user_id' => $user_id,
'unused_accounts' => [what do I insert here?]
);
$this->teacher_data_model->add_accounts($data, $user_id);
redirect('teacher', 'refresh');
}
This function is admittedly sloppy, I am still fairly new to this. This function gets the user ID and passes it to a model that uses it to find our teacher and update the number of student accounts they have. So far this works as long as I have a fixed value for 'unused_accounts', the problem is when I do this:
public function add_account()
{
// Getter of the user data
$user = $this->ion_auth->user()->row();
$user_id = $user->id;
$this->load->model("teacher_data_model");
//This gets the existing accounts
$num_accounts["record"] = $this->teacher_data_model->get_unused_accounts($user_id);
$this->load->view("teacher/teacher_data_viewer", $num_accounts);
$data = array(
'user_id' => $user_id,
'unused_accounts' => [what do I insert here?]
);
// data insertion
$this->teacher_data_model->add_accounts($data, $user_id);
redirect('teacher', 'refresh');
}
I'm not sure whether to but the +1 increment in the controller or the model, but I can't even seem to identify the searched data as an int at this point.
For [what do I insert here?] if I use $num_accounts I get this database error:
Error Number: 1054
Unknown column 'Array' in 'field list'
UPDATE teachers SET user_id = '1', unused_accounts = Array WHERE user_id = '1'
Here is my model in case it's needed:
function add_accounts($data, $uid)
{
$this->db->where('user_id', $uid);
$this->db->update('teachers',$data);
}
EDIT: This is my function that gets the data from the database
function get_unused_accounts($usersid)
{
$this->db->select('unused_accounts');
$this->db->from('teachers');
$this->db->where('user_id', $usersid);
$query = $this->db->get();
return $query->result();
}
I'm not sure if this puts out data in INT form. When I was using this to check if the user has at least one account, it always accepts as true even if the user has zero accounts.
I would suggest using raw SQL in your model for this purpose:
function add_accounts($uid, $quantity = 1)
{
$this->db->query('
UPDATE teachers
SET unused_accounts=unused_accounts+'.$quantity.'
WHERE user_id='.$uid
);
}
Now you can increment unused_accounts value by one for a user using
$this->teacher_data_model->add_accounts($user_id);
or by any amount you want using
$this->teacher_data_model->add_accounts($user_id, $amount);
Not sure if CodeIgniter's ActiveRecord would accept statement unused_accounts=unused_accounts+'.$quantity.', but if it does, you can try using this in your controller it wont work, see below for an edited part:
$data = array(
'user_id' => $user_id,
'unused_accounts' => 'unused_accounts + '.$amount
);
EDIT: Looks like if you want to use ActiveRecord, you must use $this->db->set() with a third parameter set to FALSE, so something like this in your model:
function add_accounts($unused_accounts, $uid, $amount = 1)
{
$this->db->where('user_id', $uid);
$this->db->set('unused_accounts', 'unused_accounts+'.$amount, FALSE);
$this->db->update('teachers');
}
Cant answer comments yet but
if($remaining_accounts = 1)
Will allways be true, try:
if($remaining_accounts == 1)
See PHP manual for comparison operators

Categories