In my Laravel-5.8, I have this table.
CREATE TABLE `appraisal_goal_types` (
`id` int(11) NOT NULL,
`name` varchar(200) NOT NULL,
`parent_id` int(11) DEFAULT NULL,
`max_score` int(11) DEFAULT 0,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Then I created this controller to store record in another table.
public function store(StoreAppraisalGoalRequest $request)
{
$appraisalStartDate = Carbon::parse($request->appraisal_start_date);
$appraisalEndDate = Carbon::parse($request->appraisal_end_date);
$userCompany = Auth::user()->company_id;
$employeeId = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();
try {
$goal = new AppraisalGoal();
$goal->goal_type_id = $request->goal_type_id;
$goal->appraisal_identity_id = $request->appraisal_identity_id;
$goal->employee_id = $employeeId; //$request->employees_id
$goal->weighted_score = $request->weighted_score;
$goal->goal_title = $request->goal_title;
$goal->goal_description = $request->goal_description;
$goal->company_id = Auth::user()->company_id;
$goal->created_by = Auth::user()->id;
$goal->created_at = date("Y-m-d H:i:s");
$goal->is_active = 1;
if ($request->appraisal_doc != "") {
$appraisal_doc = $request->file('appraisal_doc');
$new_name = rand() . '.' . $appraisal_doc->getClientOriginalExtension();
$appraisal_doc->move(public_path('storage/documents/appraisal_goal'), $new_name);
$goal->appraisal_doc = $new_name;
}
$goal->save();
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->update(['parent_id' => $parentid]);
}
As soon as the record is saved, I want to quickly query appraisal_goal_types
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->update(['parent_id' => $parentid]);
and update the record.
I need only one row there where the answer is true. I used the code above, but nothing is happening.
How do I resolve this?
Thank you
Try like this,
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
$goal->parent_id = $parentid;
$goal->save();
There is an another solution like this,
$parentids = DB::table('appraisal_goal_types')->select('parent_id')->whereNotNull('parent_id')->where('company_id', $userCompany)->where('id', $goal->goal_type_id)->first();
$parentid = $parentids->id;
AppraisalGoal::where('id', $goal->id)->update(['parent_id' => $parentid]);
Both will works. And let me know if you solved the issue
I have custom code to get vacancies:
Laravel Eloquent query:
$vacancy = new Vacancy;
$vacancy = $vacancy->has('user')->orWhere('is_express', 1);
$where = [];
$date = Carbon::now()->subDays(10);
$where[] = ['deleted_at', null];
$where[] = ['updated_at', '>=', $date];
$employment = [0];
$vacancy = $vacancy->whereIn('employment', $employment);
$vacancy = $vacancy->where($where)->get();
SQL code:
select * from `vacancies`
where(exists(select * from `users`
where `vacancies`.
`user_id` = `users`.
`id`
and `users`.
`deleted_at`
is null) or `is_express` = 1 and `employment` in ( 0 ) and(`deleted_at`
is null and `updated_at` >= '2019-03-22 08:48:34' )) and `vacancies`.
`deleted_at`
is null
Here is my table structure.
When I run this code or SQL query return vacancies with any employment. For example here in my code I need to vacancies with only employment = 0 but my current result return vacancies with any employments.
Where I have error in my code?
Can you please try this:
$vacancy = Vacancy::whereNull('deleted_at')->where('updated_at', '>=', $date)
->whereIn('employment', $employment)
->where(function($query) {
return $query->has('user')->orWhere('is_express', 1);
});
I am parsing currency rates from a rss.xml feed that all works great. I am now trying to insert that data into a database called rates with a table called tblRates. I keep getting this error and do not know why. Here is the function in the model I am using to try to batch insert into the database.
function addIQDRates($Data){
if($this->db->insert_batch('tblRates', $Data, 'Currency'))
{
return $this->db->affected_rows();
}else{
return FALSE;
}
}
Also here is the foreach statement I am using in my controller to sort the data from the xml file and to insert it into the database.
$Data = array();
$Data = array();
$Count = 0;
foreach ($xml->channel->item as $currencyInfo) {
$Data[$Count]['Currency'] = trim(str_replace("/USD", "", $currencyInfo->title)); // UNIQUE
$Data[$Count]['PubDate'] = date('Y-m-d H:i:s', strtotime(trim($currencyInfo->pubDate)));
$Data['CXRate'] = trim(preg_replace("/[^0-9,.]/", "", str_replace("1 United States Dollar = ", "", $currencyInfo->description)));
$Data[$Count]['DateCreated'] = date('Y-m-d H:i:s');
$Count++;
}
$TotalRows = $this->mycron_model->addIQDRates($Data);
Also here is my Create Table statement
CREATE TABLE IF NOT EXISTS `tblRates` (
`RateID` int(11) NOT NULL AUTO_INCREMENT,
`Currency` varchar(50) NOT NULL,
`PubDate` datetime NOT NULL,
`CXRate` int(11) NOT NULL,
`DateCreated` datetime NOT NULL,
PRIMARY KEY (`RateID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
all help greatly appreciated.
I am not sure, you might have written $Data['CXRate'] instead of $Data[$Count]['CXRate'].
So the loop should like like below:
foreach ($xml->channel->item as $currencyInfo) {
$Data[$Count]['Currency'] = trim(str_replace("/USD", "", $currencyInfo->title)); // UNIQUE
$Data[$Count]['PubDate'] = date('Y-m-d H:i:s', strtotime(trim($currencyInfo->pubDate)));
$Data[$Count]['CXRate'] = trim(preg_replace("/[^0-9,.]/", "", str_replace("1 United States Dollar = ", "", $currencyInfo->description)));
$Data[$Count]['DateCreated'] = date('Y-m-d H:i:s');
$Count++;
}
I have a table:
*CREATE TABLE IF NOT EXISTS `blogs_settings` (
`blog_id` int(11) NOT NULL AUTO_INCREMENT,
`owner_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`meta_description` text NOT NULL,
`meta_keywords` text NOT NULL,
`theme` varchar(25) NOT NULL DEFAULT 'default',
`is_active` tinyint(1) NOT NULL DEFAULT '1',
`date_created` int(11) NOT NULL,
PRIMARY KEY (`blog_id`),
KEY `owner_id` (`owner_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;*
And the second table:
*CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(128) NOT NULL,
`sex` tinyint(1) NOT NULL,
`birthday` date NOT NULL,
`avatar_id` int(11) DEFAULT NULL,
`user_level` tinyint(1) NOT NULL DEFAULT '1',
`date_registered` int(11) NOT NULL,
`is_active` tinyint(1) NOT NULL DEFAULT '0',
`is_banned` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`),
KEY `is_active` (`is_active`),
KEY `user_level` (`user_level`),
KEY `is_banned` (`is_banned`),
KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;*
How may I select all the fields from blogs_settings table and join only the 'username' field from the users table using TableGateway in ZF2, on blogs_settings.owner_id = users.user_id. Thanks in advance. Your help is much appreciated.
EDIT:
namespace Object\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
class BlogsSettingsTable {
protected $tableGateway;
protected $select;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
$this->select = new Select();
}
public function getBlogs($field = '', $value = '') {
$resultSet = $this->tableGateway->select(function(Select $select) {
$select->join('users', 'blogs_settings.owner_id = users.user_id', array('username'));
});
return $resultSet;
}
public function getBlog($blogID) {
$id = (int) $blogID;
$rowset = $this->tableGateway->select(array('blog_id' => $id));
$row = $rowset->current();
if (!$row) {
throw new Exception('Could not find row with ID = ' . $id);
}
return $row;
}
public function addBlog(BlogsSettings $blog) {
$data = array(
'owner_id' => $blog->owner_id,
'title' => $blog->title,
'meta_description' => $blog->meta_description,
'meta_keywords' => $blog->meta_keywords,
'theme' => $blog->theme,
'is_active' => $blog->is_active,
'date_created' => $blog->date_created,
);
$this->tableGateway->insert($data);
}
public function deleteBlog($blogID) {
return $this->tableGateway->delete(array('blog_id' => $blogID));
}
}
With this, it executes the following query:
SELECT blogs_settings.*, users.username AS username FROM blogs_settings INNER JOIN users ON blogs_settings.owner_id = users.user_id
but the resultSet does not contain the username field from the joined 'users' table. However, when I run the query in phpmyadmin, everything is okay and I have the 'username' field from the 'users' table joined. What's the problem?
EDIT 2
ok, I now tried the following:
public function getBlogs() {
$select = $this->tableGateway->getSql()->select();
$select->columns(array('blog_id', 'interest_id', 'owner_id', 'title', 'date_created'));
$select->join('users', 'users.user_id = blogs_settings.owner_id', array('username'), 'left');
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
the executed query is:
SELECT `blogs_settings`.`blog_id` AS `blog_id`, `blogs_settings`.`interest_id` AS `interest_id`, `blogs_settings`.`owner_id` AS `owner_id`, `blogs_settings`.`title` AS `title`, `blogs_settings`.`date_created` AS `date_created`, `users`.`username` AS `username` FROM `blogs_settings` LEFT JOIN `users` ON `users`.`user_id` = `blogs_settings`.`owner_id`
When I run it into phpmyadmin, it joins the username field from the users table. When in zf2, it doesn't.
Here's the dump of the whole object:
Zend\Db\ResultSet\ResultSet Object
(
[allowedReturnTypes:protected] => Array
(
[0] => arrayobject
[1] => array
)
[arrayObjectPrototype:protected] => Object\Model\BlogsSettings Object
(
[blog_id] =>
[interest_id] =>
[owner_id] =>
[title] =>
[meta_description] =>
[meta_keywords] =>
[theme] =>
[is_active] =>
[date_created] =>
)
[returnType:protected] => arrayobject
[buffer:protected] =>
[count:protected] => 1
[dataSource:protected] => Zend\Db\Adapter\Driver\Pdo\Result Object
(
[statementMode:protected] => forward
[resource:protected] => PDOStatement Object
(
[queryString] => SELECT `blogs_settings`.`blog_id` AS `blog_id`, `blogs_settings`.`interest_id` AS `interest_id`, `blogs_settings`.`owner_id` AS `owner_id`, `blogs_settings`.`title` AS `title`, `blogs_settings`.`date_created` AS `date_created`, `users`.`username` AS `username` FROM `blogs_settings` LEFT JOIN `users` ON `users`.`user_id` = `blogs_settings`.`owner_id`
)
[options:protected] =>
[currentComplete:protected] =>
[currentData:protected] =>
[position:protected] => -1
[generatedValue:protected] => 0
[rowCount:protected] => 1
)
[fieldCount:protected] => 6
[position:protected] =>
)
Up... any ideas?
Adding to #samsonasik's answer and addressing the issues in its comments. You won't be able to get the joined values out of what is returned from that statement. That statement returns the model object which won't have the joined rows. You'll need to execute it as SQL at a level which will prepare it as raw SQL and return you each resulting row as an array rather than an object:
$sqlSelect = $this->tableGateway->getSql()->select();
$sqlSelect->columns(array('column_name_yourtable'));
$sqlSelect->join('othertable', 'othertable.id = yourtable.id', array('column_name_othertable'), 'left');
$statement = $this->tableGateway->getSql()->prepareStatementForSqlObject($sqlSelect);
$resultSet = $statement->execute();
return $resultSet;
//then in your controller or view:
foreach($resultSet as $row){
print_r($row['column_name_yourtable']);
print_r($row['column_name_othertable']);
}
if you're using TableGateway, you can select join like this
$sqlSelect = $this->tableGateway->getSql()->select();
$sqlSelect->columns(array('column_name'));
$sqlSelect->join('othertable', 'othertable.id = yourtable.id', array(), 'left');
$resultSet = $this->tableGateway->selectWith($sqlSelect);
return $resultSet;
You have to include username field in the BlogsSetting Model that is used as model from BlogsSettingTable (The TableGateway)
class BlogsSetting {
public $blog_id;
public $interest_id;
public $owner_id;
public $title;
public $meta_description;
public $meta_keywords;
public $theme;
public $is_active;
public $date_created;
public $username;
public function exchangeArray($data)
{
// Create exchangeArray
}
}
Hope this helps
This is the exact need for both Join and Where clauses with tableGateway.
public function getEmployeefunctionDetails($empFunctionId) {
$empFunctionId = ( int ) $empFunctionId;
//echo '<pre>'; print_r($this->tableGateway->getTable()); exit;
$where = new Where();
$where->equalTo('FUNCTION_ID', $empFunctionId);
$sqlSelect = $this->tableGateway->getSql()->select()->where($where);
$sqlSelect->columns(array('FUNCTION_ID'));
$sqlSelect->join('DEPARTMENTS', 'DEPARTMENTS.DEPARTMENT_ID = EMPLOYEE_FUNCTIONS.DEPARTMENT_ID', array('DEPARTMENT_ID','DEPARTMENT_NAME'), 'inner');
$sqlSelect->join('ROLES', 'ROLES.ROLE_ID = EMPLOYEE_FUNCTIONS.ROLE_ID', array('ROLE_ID','ROLE_NAME'), 'inner');
//echo $sqlSelect->getSqlString(); exit;
$resultSet = $this->tableGateway->selectWith($sqlSelect);
if (! $resultSet) {
throw new \Exception ( "Could not find row $empFunctionId" );
}
return $resultSet->toArray();
}
In your class inherited from AbstractTableGateway u can use Select with Closure like this:
use Zend\Db\Sql\Select;
...
public function getAllBlockSettings()
{
$resultSet = $this->select(function(Select $select) {
$select->join('users', 'blogs_settings.owner_id = users.user_id', array('username'));
});
return $resultSet;
}
Give it a try:
namespace Object\Model;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;
class BlogsSettingsTbl extends AbstractTableGateway {
public function __construct($adapter) {
$this->table = 'blogs_settings';
$this->adapter = $adapter;
$this->initialize();
}
public function fetchAll() {
$where = array(); // If have any criteria
$result = $this->select(function (Select $select) use ($where) {
$select->join('users', 'blogs_settings.owner_id = users.user_id', array('username'));
//echo $select->getSqlString(); // see the sql query
});
return $result;
}
}
Add to 'getServiceConfig()' in Module.php:
'Object\Model\BlogsSettingsTbl' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new BlogsSettingsTbl($dbAdapter); // <-- also add this to 'USE' at top
return $table;
},
since the OP hasn't accepted any answer, I'll try to give the solution.
I face the same solution as the OP states and the only way to fix it is by adding this line to the model class (in this case this might be 'Blogsetttings.php').
$this->username= (!empty($data['username'])) ? $data['username'] : null;
you should add above line to the exchangeArray() method.
Hope it helps
session_start();
if(!$_SESSION['user_id'])
{
$_SESSION['user_id'] = rand(1, 1000000);
include 'database_connect.php';
mysql_query('INSERT INTO product_views (user_session_id)
VALUES
('.$_SESSION['user_id'].')');
}
$productid = $_GET['name'];
$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].'';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE user_session_id="'.$_SESSION['user_id'].'"');
}
My field modelNumber is set to null, and I am performing an Update via the last query.
Do you think that since the default value is null, it is therefore not allowing an insertion?
My table structure:
CREATE TABLE `product_views` (
`id` int(10) DEFAULT NULL,
`user_session_id` int(11) DEFAULT NULL,
`product_id` varchar(100) DEFAULT NULL,
`view_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`modelNumber` varchar(...
I'm confused:
$query = 'SELECT * FROM product_views WHERE user_session_id = '.$_SESSION['user_id'].'';
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
mysql_query('UPDATE product_views SET modelNumber="'.$productid.'" WHERE user_session_id="'.$_SESSION['user_id'].'"');
}
Why are you looping through this result set if you're not even using $row?
Edit: I think this is what you're really trying to do:
session_start();
if(!$_SESSION['user_id'])
{
// Get the user ID
$_SESSION['user_id'] = rand(1, 1000000);
require_once('database_connect.php');
// Get the model number and escape it to prevent SQL injection
$model_number = mysql_real_escape_string($_GET['name']);
// Insert a row that associates the user_id with the model number
mysql_query("INSERT INTO product_views (user_session_id,modelNumber) VALUES('{$_SESSION['user_id']}', '$model_number')");
}